package management

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"reflect"
	"strconv"
	"strings"
	"time"

	"github.com/gorilla/mux"
	"github.com/jsrccb/nachuan/common"
	"github.com/tealeg/xlsx"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func initCustomMgrApi(r *mux.Router) {
	s := r.PathPrefix("/custom").Subrouter()
	// s.HandleFunc("/list", UserListHandler)
	s.HandleFunc("/updsave", handleCustomSave)

	s.HandleFunc("/updaccountantbatch", handleUpdaccountantBatch)            //主管会计
	s.HandleFunc("/updrescustommgrbatch", handleResCustomMgrUpdBatch)        //负责客户经理
	s.HandleFunc("/updcustommgrbatch", handleCustomMgrUpdBatch)              //客户经理
	s.HandleFunc("/updbillingaccountantbatch", handleBillingAccountantBatch) //开票会计
	s.HandleFunc("/updentryaccountantbatch", handleEntryAccountantBatch)     //记账会计
	s.HandleFunc("/updcheckerbatch", handleCheckerBatch)                     //批量更新年检专员
	// s.HandleFunc("/updcustommgrbatch", handleCustomMgrUpdBatch)

	s.HandleFunc("/updcheckstatus", handleUpdCheckStatus) //更新年检状态
	//请求/order/handleOrderqueryall?ordertype=xxx&skip=1&limit=1
	s.HandleFunc("/query", handleCustomquery)
	s.HandleFunc("/download", handleDownloadCustomInfo)

	s.HandleFunc("/querynilaccountant", handleNilAccountant)
	s.HandleFunc("/querynilentryaccountant", handleNilEntryAccountant)
	s.HandleFunc("/querynilagentfeeenddate", handleNilAgentFeeEndDate)
	s.HandleFunc("/querycustomlistagentfeeflooraccountant", handleOperatingAgentFeeAccountant)
	s.HandleFunc("/querycustomlist2monago", handleOpera2MonAgoList)

	// s.HandleFunc("/del", handleOrderdel)
	s.HandleFunc("/opercustomfloor", handleOperatingCustomFloor)
	s.HandleFunc("/opercustomagentfeefloor", handleOperatingAgentFeeFloor)
	s.HandleFunc("/operaccountantfloor", handleOperatingAccountantFloor)
	s.HandleFunc("/opermycustomfloor", handleOperatingMyCustomFloor)

	ents := r.PathPrefix("/agentcustomevent").Subrouter()
	ents.HandleFunc("/queryall", handleOrderEventqueryall)

	custax := r.PathPrefix("/customtax").Subrouter()
	custax.HandleFunc("/updsave", handleCustaxSave)
	custax.HandleFunc("/query", handleCustaxQuery)
	custax.HandleFunc("/download", handleDonwloadCustaxInfo)
	custax.HandleFunc("/querycustomhistax", handleHisCustaxQuery)

	certi := r.PathPrefix("/certi").Subrouter()
	certi.HandleFunc("/updsave", handleCertiSave)
	certi.HandleFunc("/query", handleCertiQuery)
	certi.HandleFunc("/querycertihis", handleHisCertiQuery)
}

func handleOperatingMyCustomFloor(resp http.ResponseWriter, req *http.Request) {
	var (
		err   error
		bytes []byte
		// entcluests  string
		// custommgr string
		// rolelimit     *common.RoleLimits

		mycustomcount      int64 // 客户总量
		mycustomcounttoday int64 // 当日客户数
		mycustomcountmon   int64 // 当月客户数
		accountant         string
		// entryaccountant    string
		querySet  []bson.M
		queryBson bson.M
	)
	cluemap := make(map[string]interface{})
	query := req.URL.Query()
	accountant = query.Get("accountant")
	// entryaccountant = query.Get("entryaccountant")

	if accountant != "" {
		qaccountant := bson.M{"accountant": accountant}
		querySet = append(querySet, qaccountant)
	}

	querySet = append(querySet, bson.M{"agentStatus": "正常"})
	queryBson = bson.M{"$and": querySet}

	//获取总客户数量
	if mycustomcount, err = G_CustomMgr.countCustombySet(queryBson); err != nil {
		goto ERR
	}

	if mycustomcounttoday, err = G_CustomMgr.getOperMycustomDayCount(accountant); err != nil {
		goto ERR
	}

	if mycustomcountmon, err = G_CustomMgr.getOperMycustomMonCount(accountant); err != nil {
		goto ERR
	}

	cluemap["mycustomcount"] = mycustomcount
	cluemap["mycustomcounttoday"] = mycustomcounttoday
	cluemap["mycustomcountmon"] = mycustomcountmon
	if bytes, err = common.BuildResponse(0, "success", cluemap); err == nil {
		resp.Write(bytes)
	} else {
		goto ERR
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

func (customMgr *CustomMgr) getOperMycustomDayCount(accountant string) (countCustom int64, err error) {
	var (
		// resultOne *mongo.InsertOneResult
		ctx context.Context
		// update *common.HostInfo
		daystr    string
		querySet  []bson.M
		queryBson bson.M
	)
	ctx, _ = context.WithTimeout(context.Background(), 15*time.Second)
	daystr = common.BuildDateTodayStr2()

	querySet = append(querySet, bson.M{"accountant": accountant})
	querySet = append(querySet, bson.M{"agentStatus": "正常"})
	querySet = append(querySet, bson.M{"accountantChangeTime": bson.M{"$regex": daystr, "$options": "$i"}})

	queryBson = bson.M{"$and": querySet}
	// countCustom, err = customMgr.CustomColl.CountDocuments(ctx, bson.M{"accountant": accountant, "agentStatus": "正常", "accountantChangeTime": bson.M{"$regex": monstr, "$options": "$i"}})
	countCustom, err = customMgr.CustomColl.CountDocuments(ctx, queryBson)

	return
}

func (customMgr *CustomMgr) getOperMycustomMonCount(accountant string) (countCustom int64, err error) {
	var (
		// resultOne *mongo.InsertOneResult
		ctx context.Context
		// update *common.HostInfo
		monstr string

		querySet  []bson.M
		queryBson bson.M
	)
	ctx, _ = context.WithTimeout(context.Background(), 15*time.Second)
	monstr = common.BuildDateMonStr2()
	// countCustom, err = customMgr.CustomColl.CountDocuments(ctx, bson.M{"accountant": accountant, "agentStatus": "正常", "accountantChangeTime": bson.M{"$regex": monstr, "$options": "$i"}})
	querySet = append(querySet, bson.M{"accountant": accountant})
	querySet = append(querySet, bson.M{"agentStatus": "正常"})
	querySet = append(querySet, bson.M{"accountantChangeTime": bson.M{"$regex": monstr, "$options": "$i"}})

	queryBson = bson.M{"$and": querySet}
	// countCustom, err = customMgr.CustomColl.CountDocuments(ctx, bson.M{"accountant": accountant, "agentStatus": "正常", "accountantChangeTime": bson.M{"$regex": monstr, "$options": "$i"}})
	countCustom, err = customMgr.CustomColl.CountDocuments(ctx, queryBson)

	return
}

func handleNilAgentFeeEndDate(resp http.ResponseWriter, req *http.Request) {
	var (
		err   error
		bytes []byte
		// entcluests  string
		// custommgr string
		// rolelimit     *common.RoleLimits

		skip       int
		limit      int
		skipParam  string
		limitParam string
		count      int64                 //待分主管会计
		customlist []*common.AgentCustom //待分记账会计

	)
	cluemap := make(map[string]interface{})

	query := req.URL.Query()

	skipParam = query.Get("skip")
	limitParam = query.Get("limit")

	if skip, err = strconv.Atoi(skipParam); err != nil {
		skip = 0
	}

	if limit, err = strconv.Atoi(limitParam); err != nil {
		limit = 100

	}
	// custommgr = req.PostForm.Get("custommgr")

	if count, err = G_CustomMgr.getOperNilAgentFeeEndDateCount(); err != nil {
		goto ERR
	}

	if customlist, err = G_CustomMgr.getOperNeedNilAgentFeeEndDateList(int64(skip), int64(limit)); err != nil {
		goto ERR
	}

	cluemap["count"] = count
	cluemap["customlist"] = customlist

	if bytes, err = common.BuildResponse(0, "success", cluemap); err == nil {
		resp.Write(bytes)
	} else {
		goto ERR
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

func handleNilEntryAccountant(resp http.ResponseWriter, req *http.Request) {
	var (
		err   error
		bytes []byte
		// entcluests  string
		// custommgr string
		// rolelimit     *common.RoleLimits
		skip                int
		limit               int
		skipParam           string
		limitParam          string
		count               int64                 //待分主管会计
		entryaccountantlist []*common.AgentCustom //待分记账会计

	)
	cluemap := make(map[string]interface{})
	// custommgr = req.PostForm.Get("custommgr")

	query := req.URL.Query()

	skipParam = query.Get("skip")
	limitParam = query.Get("limit")

	if skip, err = strconv.Atoi(skipParam); err != nil {
		skip = 0
	}

	if limit, err = strconv.Atoi(limitParam); err != nil {
		limit = 100

	}

	if count, err = G_CustomMgr.getOperNeedEntryAccountantCount(); err != nil {
		goto ERR
	}

	if entryaccountantlist, err = G_CustomMgr.getOperNeedEntryAccountantCountList(int64(skip), int64(limit)); err != nil {
		goto ERR
	}

	cluemap["count"] = count
	cluemap["entryaccountantlist"] = entryaccountantlist

	if bytes, err = common.BuildResponse(0, "success", cluemap); err == nil {
		resp.Write(bytes)
	} else {
		goto ERR
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

func handleNilAccountant(resp http.ResponseWriter, req *http.Request) {
	var (
		err   error
		bytes []byte
		// entcluests  string
		// custommgr string
		// rolelimit     *common.RoleLimits

		skipParam      string
		limitParam     string
		count          int64                 //待分主管会计
		accountantlist []*common.AgentCustom //待分记账会计

		skip  int
		limit int
	)
	cluemap := make(map[string]interface{})

	query := req.URL.Query()

	skipParam = query.Get("skip")
	limitParam = query.Get("limit")

	if skip, err = strconv.Atoi(skipParam); err != nil {
		skip = 0
	}

	if limit, err = strconv.Atoi(limitParam); err != nil {
		limit = 100

	}

	// custommgr = req.PostForm.Get("custommgr")

	if count, err = G_CustomMgr.getOperNeedAccountantCount(); err != nil {
		goto ERR
	}

	if accountantlist, err = G_CustomMgr.getOperNeedAccountantCountList(int64(skip), int64(limit)); err != nil {
		goto ERR
	}

	cluemap["count"] = count
	cluemap["accountantlist"] = accountantlist

	if bytes, err = common.BuildResponse(0, "success", cluemap); err == nil {
		resp.Write(bytes)
	} else {
		goto ERR
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

func handleOperatingAccountantFloor(resp http.ResponseWriter, req *http.Request) {
	var (
		err   error
		bytes []byte
		// entcluests  string
		// custommgr string
		// rolelimit     *common.RoleLimits

		needaccountantcount      int64 //待分主管会计
		needentryaccountantcount int64 //待分记账会计

	)
	cluemap := make(map[string]interface{})
	if err = req.ParseForm(); err != nil {
		goto ERR
	}
	// custommgr = req.PostForm.Get("custommgr")

	if needaccountantcount, err = G_CustomMgr.getOperNeedAccountantCount(); err != nil {
		goto ERR
	}
	if needentryaccountantcount, err = G_CustomMgr.getOperNeedEntryAccountantCount(); err != nil {
		goto ERR
	}

	cluemap["needaccountantcount"] = needaccountantcount
	cluemap["needentryaccountantcount"] = needentryaccountantcount

	if bytes, err = common.BuildResponse(0, "success", cluemap); err == nil {
		resp.Write(bytes)
	} else {
		goto ERR
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

func (customMgr *CustomMgr) getOperOneMonAccountantCountList(accountant string, skip int64, limit int64) (customs []*common.AgentCustom, err error) {
	var (
		// resultOne *mongo.InsertOneResult
		ctx context.Context
		// update *common.HostInfo
		custom  *common.AgentCustom
		cursor  *mongo.Cursor
		findopt *options.FindOptions
	)
	ctx, _ = context.WithTimeout(context.Background(), 15*time.Second)

	findopt = &options.FindOptions{}

	if limit > 0 && skip >= 0 {
		findopt.SetLimit(limit)
		findopt.SetSkip(limit * skip)
	} else {
		return
	}
	mon1str := common.BuildDateLast1Monstr()
	filter := bson.D{{"$and", []interface{}{bson.D{{"$or", []interface{}{bson.M{"agentFeeEndDate": bson.M{"$regex": mon1str, "$options": "$i"}}, bson.D{{"agentFeeEndDate", ""}}}}}, bson.M{"agentStatus": "正常"}, bson.M{"accountant": accountant}}}}

	cursor, err = customMgr.CustomColl.Find(ctx, filter, findopt)
	defer cursor.Close(ctx)

	for cursor.Next(ctx) {
		custom = &common.AgentCustom{}
		if err = cursor.Decode(custom); err != nil {
			continue
		}
		customs = append(customs, custom)
	}
	return
}

func (customMgr *CustomMgr) getOperNeedEntryAccountantCountList(skip int64, limit int64) (customs []*common.AgentCustom, err error) {
	var (
		// resultOne *mongo.InsertOneResult
		ctx context.Context
		// update *common.HostInfo
		custom  *common.AgentCustom
		cursor  *mongo.Cursor
		findopt *options.FindOptions
	)
	ctx, _ = context.WithTimeout(context.Background(), 15*time.Second)

	findopt = &options.FindOptions{}

	if limit > 0 && skip >= 0 {
		findopt.SetLimit(limit)
		findopt.SetSkip(limit * skip)
	} else {
		return
	}

	cursor, err = customMgr.CustomColl.Find(ctx, bson.M{"entryAccountant": ""}, findopt)
	defer cursor.Close(ctx)

	for cursor.Next(ctx) {
		custom = &common.AgentCustom{}
		if err = cursor.Decode(custom); err != nil {
			continue
		}
		customs = append(customs, custom)
	}
	return
}

func (customMgr *CustomMgr) getOperNeedNilAgentFeeEndDateList(skip int64, limit int64) (customs []*common.AgentCustom, err error) {
	var (
		// resultOne *mongo.InsertOneResult
		ctx context.Context
		// update *common.HostInfo
		custom  *common.AgentCustom
		cursor  *mongo.Cursor
		findopt *options.FindOptions
	)
	ctx, _ = context.WithTimeout(context.Background(), 15*time.Second)
	findopt = &options.FindOptions{}

	if limit > 0 && skip >= 0 {
		findopt.SetLimit(limit)
		findopt.SetSkip(limit * skip)
	} else {
		return
	}
	mon1str := common.BuildDateLast1Monstr()
	filter := bson.D{{"$and", []interface{}{bson.D{{"$or", []interface{}{bson.M{"agentFeeEndDate": bson.M{"$regex": mon1str, "$options": "$i"}}, bson.D{{"agentFeeEndDate", ""}}}}}, bson.M{"agentStatus": "正常"}}}}
	cursor, err = customMgr.CustomColl.Find(ctx, filter, findopt)
	defer cursor.Close(ctx)

	for cursor.Next(ctx) {
		custom = &common.AgentCustom{}
		if err = cursor.Decode(custom); err != nil {
			continue
		}
		customs = append(customs, custom)
	}
	return
}

func (customMgr *CustomMgr) getOperNeedAccountantCountList(skip int64, limit int64) (customs []*common.AgentCustom, err error) {
	var (
		// resultOne *mongo.InsertOneResult
		ctx context.Context
		// update *common.HostInfo
		findopt *options.FindOptions
		custom  *common.AgentCustom
		cursor  *mongo.Cursor
	)
	ctx, _ = context.WithTimeout(context.Background(), 15*time.Second)

	findopt = &options.FindOptions{}

	if limit > 0 && skip >= 0 {
		findopt.SetLimit(limit)
		findopt.SetSkip(limit * skip)
	} else {
		return
	}

	cursor, err = customMgr.CustomColl.Find(ctx, bson.M{"accountant": ""}, findopt)
	defer cursor.Close(ctx)

	for cursor.Next(ctx) {
		custom = &common.AgentCustom{}
		if err = cursor.Decode(custom); err != nil {
			continue
		}
		customs = append(customs, custom)
	}
	return
}

func (customMgr *CustomMgr) getOperNilAgentFeeEndDateCount() (countCustom int64, err error) {
	var (
		// resultOne *mongo.InsertOneResult
		ctx context.Context
		// update *common.HostInfo
	)
	ctx, _ = context.WithTimeout(context.Background(), 15*time.Second)
	mon1str := common.BuildDateLast1Monstr()

	filter := bson.D{{"$and", []interface{}{bson.D{{"$or", []interface{}{bson.M{"agentFeeEndDate": bson.M{"$regex": mon1str, "$options": "$i"}}, bson.D{{"agentFeeEndDate", ""}}}}}, bson.M{"agentStatus": "正常"}}}}

	countCustom, err = customMgr.CustomColl.CountDocuments(ctx, filter)

	return
}

func (customMgr *CustomMgr) getOperNeedAccountantCount() (countCustom int64, err error) {
	var (
		// resultOne *mongo.InsertOneResult
		ctx context.Context
		// update *common.HostInfo
	)
	ctx, _ = context.WithTimeout(context.Background(), 15*time.Second)

	countCustom, err = customMgr.CustomColl.CountDocuments(ctx, bson.M{"accountant": ""})

	return
}

func (customMgr *CustomMgr) getOperNeedEntryAccountantCount() (countCustom int64, err error) {
	var (
		// resultOne *mongo.InsertOneResult
		ctx context.Context
		// update *common.HostInfo
	)
	ctx, _ = context.WithTimeout(context.Background(), 15*time.Second)

	countCustom, err = customMgr.CustomColl.CountDocuments(ctx, bson.M{"entryAccountant": ""})

	return
}
func handleOpera2MonAgoList(resp http.ResponseWriter, req *http.Request) {
	var (
		err   error
		bytes []byte
		// entcluests  string
		accountant string
		// rolelimit     *common.RoleLimits
		skipParam  string
		limitParam string
		skip       int
		limit      int
		count      int64
		// agentfeecount        int64 //应回款总量
		customlist []*common.AgentCustom //待分记账会计

	)
	cluemap := make(map[string]interface{})
	query := req.URL.Query()

	skipParam = query.Get("skip")
	limitParam = query.Get("limit")
	accountant = query.Get("accountant")

	if skip, err = strconv.Atoi(skipParam); err != nil {
		skip = 0
	}

	if limit, err = strconv.Atoi(limitParam); err != nil {
		limit = 100

	}

	if accountant == "" {

		if count, err = G_CustomMgr.getOperAgentFeeCount2Monago(); err != nil {
			goto ERR
		}

		if customlist, err = G_CustomMgr.getOper2MonList(int64(skip), int64(limit)); err != nil {
			goto ERR
		}
	} else {

		if count, err = G_CustomMgr.getOperAgentFeeCount2MonagoAccountant(accountant); err != nil {
			goto ERR
		}

		if customlist, err = G_CustomMgr.getOper2MonAccountantList(accountant, int64(skip), int64(limit)); err != nil {
			goto ERR
		}
	}

	cluemap["count"] = count
	cluemap["customlist"] = customlist

	if bytes, err = common.BuildResponse(0, "success", cluemap); err == nil {
		resp.Write(bytes)
	} else {
		goto ERR
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

func (customMgr *CustomMgr) getOper2MonList(skip int64, limit int64) (customs []*common.AgentCustom, err error) {
	var (
		// resultOne *mongo.InsertOneResult
		ctx context.Context
		// update *common.HostInfo
		findopt *options.FindOptions
		custom  *common.AgentCustom
		cursor  *mongo.Cursor
		mon2str string
	)
	ctx, _ = context.WithTimeout(context.Background(), 15*time.Second)

	findopt = &options.FindOptions{}

	if limit > 0 && skip >= 0 {
		findopt.SetLimit(limit)
		findopt.SetSkip(limit * skip)
	} else {
		return
	}
	mon2str = common.BuildDateLast2Monstr() + "-31"
	filter := bson.D{{"$and", []interface{}{bson.M{"agentFeeEndDate": bson.M{"$lte": mon2str}}, bson.M{"agentFeeEndDate": bson.M{"$ne": ""}}, bson.M{"agentStatus": "正常"}}}}

	cursor, err = customMgr.CustomColl.Find(ctx, filter, findopt)
	defer cursor.Close(ctx)

	for cursor.Next(ctx) {
		custom = &common.AgentCustom{}
		if err = cursor.Decode(custom); err != nil {
			continue
		}
		customs = append(customs, custom)
	}
	return
}

func (customMgr *CustomMgr) getOper2MonAccountantList(accountant string, skip int64, limit int64) (customs []*common.AgentCustom, err error) {
	var (
		// resultOne *mongo.InsertOneResult
		ctx context.Context
		// update *common.HostInfo
		findopt *options.FindOptions
		custom  *common.AgentCustom
		cursor  *mongo.Cursor
		mon2str string
	)
	ctx, _ = context.WithTimeout(context.Background(), 15*time.Second)

	findopt = &options.FindOptions{}

	if limit > 0 && skip >= 0 {
		findopt.SetLimit(limit)
		findopt.SetSkip(limit * skip)
	} else {
		return
	}
	mon2str = common.BuildDateLast2Monstr() + "-31"
	// fmt.Println(mon2str)
	filter := bson.D{{"$and", []interface{}{bson.M{"agentFeeEndDate": bson.M{"$lte": mon2str}}, bson.M{"agentFeeEndDate": bson.M{"$ne": ""}}, bson.M{"agentStatus": "正常"}, bson.M{"accountant": accountant}}}}

	cursor, err = customMgr.CustomColl.Find(ctx, filter, findopt)
	defer cursor.Close(ctx)

	for cursor.Next(ctx) {
		custom = &common.AgentCustom{}
		if err = cursor.Decode(custom); err != nil {
			continue
		}
		customs = append(customs, custom)
	}
	return
}

func handleOperatingAgentFeeAccountant(resp http.ResponseWriter, req *http.Request) {
	var (
		err   error
		bytes []byte
		// entcluests  string
		accountant string
		// rolelimit     *common.RoleLimits
		skipParam  string
		limitParam string
		skip       int
		limit      int
		count      int64
		// agentfeecount        int64 //应回款总量
		accountantlist []*common.AgentCustom //待分记账会计

	)
	cluemap := make(map[string]interface{})
	// custommgr = req.PostForm.Get("custommgr")

	query := req.URL.Query()

	skipParam = query.Get("skip")
	limitParam = query.Get("limit")
	accountant = query.Get("accountant")

	if skip, err = strconv.Atoi(skipParam); err != nil {
		skip = 0
	}

	if limit, err = strconv.Atoi(limitParam); err != nil {
		limit = 100

	}

	if count, err = G_CustomMgr.getOperAgentFeeCount1MonagoAccountant(accountant); err != nil {
		goto ERR
	}

	if accountantlist, err = G_CustomMgr.getOperOneMonAccountantCountList(accountant, int64(skip), int64(limit)); err != nil {
		goto ERR
	}

	cluemap["count"] = count
	cluemap["accountantlist"] = accountantlist

	if bytes, err = common.BuildResponse(0, "success", cluemap); err == nil {
		resp.Write(bytes)
	} else {
		goto ERR
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

func handleOperatingAgentFeeFloor(resp http.ResponseWriter, req *http.Request) {
	var (
		err   error
		bytes []byte
		// entcluests  string
		accountant string
		// rolelimit     *common.RoleLimits

		// agentfeecount        int64 //应回款总量
		agentfeecount2monago int64 //截止上月未回款
		agentfeecount1monago int64 //本月未回款
		agentfeecountmon     int64 // 近期需回款

	)
	cluemap := make(map[string]interface{})
	query := req.URL.Query()

	accountant = query.Get("accountant")

	if accountant == "" {
		if agentfeecount2monago, err = G_CustomMgr.getOperAgentFeeCount2Monago(); err != nil {
			goto ERR
		}
		if agentfeecount1monago, err = G_CustomMgr.getOperAgentFeeCount1Monago(); err != nil {
			goto ERR
		}
		if agentfeecountmon, err = G_CustomMgr.getOperAgentFeeCountMon(); err != nil {
			goto ERR
		}
	} else {
		if agentfeecount2monago, err = G_CustomMgr.getOperAgentFeeCount2MonagoAccountant(accountant); err != nil {
			goto ERR
		}
		if agentfeecount1monago, err = G_CustomMgr.getOperAgentFeeCount1MonagoAccountant(accountant); err != nil {
			goto ERR
		}
		if agentfeecountmon, err = G_CustomMgr.getOperAgentFeeCountMonAccountant(accountant); err != nil {
			goto ERR
		}
	}

	cluemap["agentfeecount2monago"] = agentfeecount2monago
	cluemap["agentfeecount1monago"] = agentfeecount1monago
	cluemap["agentfeecountmon"] = agentfeecountmon
	cluemap["agentfeecount"] = agentfeecount2monago + agentfeecount1monago + agentfeecountmon

	if bytes, err = common.BuildResponse(0, "success", cluemap); err == nil {
		resp.Write(bytes)
	} else {
		goto ERR
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

func (customMgr *CustomMgr) getOperAgentFeeCount2MonagoAccountant(accountant string) (countCustom int64, err error) {
	var (
		// resultOne *mongo.InsertOneResult
		ctx context.Context
		// update *common.HostInfo
		mon2str string
	)
	ctx, _ = context.WithTimeout(context.Background(), 15*time.Second)

	// fmt.Println(1)
	mon2str = common.BuildDateLast2Monstr() + "-31"
	// fmt.Println(mon2str)
	filter := bson.D{{"$and", []interface{}{bson.M{"agentFeeEndDate": bson.M{"$lte": mon2str}}, bson.M{"agentFeeEndDate": bson.M{"$ne": ""}}, bson.M{"agentStatus": "正常"}, bson.M{"accountant": accountant}}}}

	countCustom, err = customMgr.CustomColl.CountDocuments(ctx, filter)

	return
}

func (customMgr *CustomMgr) getOperAgentFeeCount1MonagoAccountant(accountant string) (countCustom int64, err error) {
	var (
		// resultOne *mongo.InsertOneResult
		ctx context.Context
		// update *common.HostInfo
		mon1str string
	)
	ctx, _ = context.WithTimeout(context.Background(), 15*time.Second)

	// fmt.Println(1)
	mon1str = common.BuildDateLast1Monstr()
	// fmt.Println(mon1str)

	// filter = bson.D{{"nickname", "张三"}, {"$or", []interface{}{bson.D{{"sex", 1}}, bson.D{{"sex", 2}}}}}
	// filter := bson.D{{"$or", []interface{}{bson.M{"agentFeeEndDate": bson.M{"$regex": mon1str, "$options": "$i"}}, bson.D{{"agentFeeEndDate", ""}}}}}
	filter := bson.D{{"$and", []interface{}{bson.D{{"$or", []interface{}{bson.M{"agentFeeEndDate": bson.M{"$regex": mon1str, "$options": "$i"}}, bson.D{{"agentFeeEndDate", ""}}}}}, bson.M{"agentStatus": "正常"}, bson.M{"accountant": accountant}}}}

	countCustom, err = customMgr.CustomColl.CountDocuments(ctx, filter)

	return
}

func (customMgr *CustomMgr) getOperAgentFeeCountMonAccountant(accountant string) (countCustom int64, err error) {
	var (
		// resultOne *mongo.InsertOneResult
		ctx context.Context
		// update *common.HostInfo
		mon1str string
		monstr  string
	)
	ctx, _ = context.WithTimeout(context.Background(), 15*time.Second)

	// fmt.Println(1)
	mon1str = common.BuildDateMore1Monstr()

	monstr = common.BuildDateMonstr()
	// fmt.Println(mon1str)
	// fmt.Println(monstr)
	// filter = bson.D{{"nickname", "张三"}, {"$or", []interface{}{bson.D{{"sex", 1}}, bson.D{{"sex", 2}}}}}
	// filter := bson.D{{"$or", []interface{}{bson.M{"agentFeeEndDate": bson.M{"$regex": mon1str, "$options": "$i"}}, bson.M{"agentFeeEndDate": bson.M{"$regex": monstr, "$options": "$i"}}}}}
	filter := bson.D{{"$and", []interface{}{bson.D{{"$or", []interface{}{bson.M{"agentFeeEndDate": bson.M{"$regex": mon1str, "$options": "$i"}}, bson.M{"agentFeeEndDate": bson.M{"$regex": monstr, "$options": "$i"}}}}}, bson.M{"agentStatus": "正常"}, bson.M{"accountant": accountant}}}}

	// filter := bson.D{{"$and", []interface{}{bson.D{{"$or", []interface{}{bson.M{"agentFeeEndDate": bson.M{"$regex": mon1str, "$options": "$i"}}, bson.M{"agentFeeEndDate": bson.M{"$regex": monstr, "$options": "$i"}}}}, bson.M{"agentStatus": "正常"}}}}

	countCustom, err = customMgr.CustomColl.CountDocuments(ctx, filter)

	return
}

func (customMgr *CustomMgr) getOperAgentFeeCount2Monago() (countCustom int64, err error) {
	var (
		// resultOne *mongo.InsertOneResult
		ctx context.Context
		// update *common.HostInfo
		mon2str string
	)
	ctx, _ = context.WithTimeout(context.Background(), 15*time.Second)

	// fmt.Println(1)
	mon2str = common.BuildDateLast2Monstr() + "-31"
	// fmt.Println(mon2str)
	filter := bson.D{{"$and", []interface{}{bson.M{"agentFeeEndDate": bson.M{"$lte": mon2str}}, bson.M{"agentFeeEndDate": bson.M{"$ne": ""}}, bson.M{"agentStatus": "正常"}}}}

	// countCustom, err = customMgr.CustomColl.CountDocuments(ctx, bson.M{"agentFeeEndDate": bson.M{"$lte": mon2str}, "agentStatus": "正常"})
	countCustom, err = customMgr.CustomColl.CountDocuments(ctx, filter)

	return
}

func (customMgr *CustomMgr) getOperAgentFeeCount1Monago() (countCustom int64, err error) {
	var (
		// resultOne *mongo.InsertOneResult
		ctx context.Context
		// update *common.HostInfo
		mon1str string
	)
	ctx, _ = context.WithTimeout(context.Background(), 15*time.Second)

	// fmt.Println(1)
	mon1str = common.BuildDateLast1Monstr()
	// fmt.Println(mon1str)

	// filter = bson.D{{"nickname", "张三"}, {"$or", []interface{}{bson.D{{"sex", 1}}, bson.D{{"sex", 2}}}}}
	// filter := bson.D{{"$or", []interface{}{bson.M{"agentFeeEndDate": bson.M{"$regex": mon1str, "$options": "$i"}}, bson.D{{"agentFeeEndDate", ""}}}}}
	filter := bson.D{{"$and", []interface{}{bson.D{{"$or", []interface{}{bson.M{"agentFeeEndDate": bson.M{"$regex": mon1str, "$options": "$i"}}, bson.D{{"agentFeeEndDate", ""}}}}}, bson.M{"agentStatus": "正常"}}}}

	countCustom, err = customMgr.CustomColl.CountDocuments(ctx, filter)

	return
}

func (customMgr *CustomMgr) getOperAgentFeeCountMon() (countCustom int64, err error) {
	var (
		// resultOne *mongo.InsertOneResult
		ctx context.Context
		// update *common.HostInfo
		mon1str string
		monstr  string
	)
	ctx, _ = context.WithTimeout(context.Background(), 15*time.Second)

	// fmt.Println(1)
	mon1str = common.BuildDateMore1Monstr()

	monstr = common.BuildDateMonstr()
	// fmt.Println(mon1str)
	// fmt.Println(monstr)
	// filter = bson.D{{"nickname", "张三"}, {"$or", []interface{}{bson.D{{"sex", 1}}, bson.D{{"sex", 2}}}}}
	// filter := bson.D{{"$or", []interface{}{bson.M{"agentFeeEndDate": bson.M{"$regex": mon1str, "$options": "$i"}}, bson.M{"agentFeeEndDate": bson.M{"$regex": monstr, "$options": "$i"}}}}}
	filter := bson.D{{"$and", []interface{}{bson.D{{"$or", []interface{}{bson.M{"agentFeeEndDate": bson.M{"$regex": mon1str, "$options": "$i"}}, bson.M{"agentFeeEndDate": bson.M{"$regex": monstr, "$options": "$i"}}}}}, bson.M{"agentStatus": "正常"}}}}

	// filter := bson.D{{"$and", []interface{}{bson.D{{"$or", []interface{}{bson.M{"agentFeeEndDate": bson.M{"$regex": mon1str, "$options": "$i"}}, bson.M{"agentFeeEndDate": bson.M{"$regex": monstr, "$options": "$i"}}}}, bson.M{"agentStatus": "正常"}}}}

	countCustom, err = customMgr.CustomColl.CountDocuments(ctx, filter)

	return
}

func handleOperatingCustomFloor(resp http.ResponseWriter, req *http.Request) {
	var (
		err   error
		bytes []byte
		// entcluests  string
		// custommgr string
		// rolelimit     *common.RoleLimits

		agentcount     int64 //代账客户总量
		agentcountNOR  int64 //代账客户正常户
		agentcountCANC int64 //本司注销户
		agentcountSTP  int64 //停报户
		agentcountOUT  int64 //已转走户

	)
	cluemap := make(map[string]interface{})
	if err = req.ParseForm(); err != nil {
		goto ERR
	}
	// custommgr = req.PostForm.Get("custommgr")

	if agentcount, err = G_CustomMgr.getOperatingCustomAll(); err != nil {
		goto ERR
	}
	if agentcountNOR, err = G_CustomMgr.getOperatingCustomNor(); err != nil {
		goto ERR
	}
	if agentcountCANC, err = G_CustomMgr.getOperatingCustomCanc(); err != nil {
		goto ERR
	}
	if agentcountSTP, err = G_CustomMgr.getOperatingCustomStp(); err != nil {
		goto ERR
	}
	if agentcountOUT, err = G_CustomMgr.getOperatingCustomOut(); err != nil {
		goto ERR
	}

	cluemap["agentcount"] = agentcount
	cluemap["agentcountNOR"] = agentcountNOR
	cluemap["agentcountCANC"] = agentcountCANC
	cluemap["agentcountSTP"] = agentcountSTP
	cluemap["agentcountOUT"] = agentcountOUT

	if bytes, err = common.BuildResponse(0, "success", cluemap); err == nil {
		resp.Write(bytes)
	} else {
		goto ERR
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

func (customMgr *CustomMgr) getOperatingCustomAll() (countCustom int64, err error) {
	var (
		// resultOne *mongo.InsertOneResult
		ctx context.Context
		// update *common.HostInfo
	)
	ctx, _ = context.WithTimeout(context.Background(), 15*time.Second)

	// fmt.Println(1)
	countCustom, err = customMgr.CustomColl.CountDocuments(ctx, bson.M{})

	return
}

func (customMgr *CustomMgr) getOperatingCustomNor() (countCustom int64, err error) {
	var (
		// resultOne *mongo.InsertOneResult
		ctx context.Context
		// update *common.HostInfo
	)
	ctx, _ = context.WithTimeout(context.Background(), 15*time.Second)

	// fmt.Println(1)
	countCustom, err = customMgr.CustomColl.CountDocuments(ctx, bson.M{"agentStatus": "正常"})

	return
}

func (customMgr *CustomMgr) getOperatingCustomCanc() (countCustom int64, err error) {
	var (
		// resultOne *mongo.InsertOneResult
		ctx context.Context
		// update *common.HostInfo
	)
	ctx, _ = context.WithTimeout(context.Background(), 15*time.Second)

	// fmt.Println(1)
	countCustom, err = customMgr.CustomColl.CountDocuments(ctx, bson.M{"agentStatus": "本司注销"})

	return
}

func (customMgr *CustomMgr) getOperatingCustomStp() (countCustom int64, err error) {
	var (
		// resultOne *mongo.InsertOneResult
		ctx context.Context
		// update *common.HostInfo
	)
	ctx, _ = context.WithTimeout(context.Background(), 15*time.Second)

	// fmt.Println(1)
	countCustom, err = customMgr.CustomColl.CountDocuments(ctx, bson.M{"agentStatus": "停报"})

	return
}

func (customMgr *CustomMgr) getOperatingCustomOut() (countCustom int64, err error) {
	var (
		// resultOne *mongo.InsertOneResult
		ctx context.Context
		// update *common.HostInfo
	)
	ctx, _ = context.WithTimeout(context.Background(), 15*time.Second)

	// fmt.Println(1)
	countCustom, err = customMgr.CustomColl.CountDocuments(ctx, bson.M{"agentStatus": "已转走"})

	return
}

type CustomMgr struct {
	client        *mongo.Client
	CustomColl    *mongo.Collection
	CustomTaxColl *mongo.Collection
	CertiColl     *mongo.Collection
}

var (
	G_CustomMgr *CustomMgr
)

func handleHisCustaxQuery(resp http.ResponseWriter, req *http.Request) {
	var (
		err   error
		bytes []byte
		// entclueinfo *common.EntClue
		querySet       []bson.M
		skipParam      string
		limitParam     string
		skip           int
		limit          int
		customtaxinfos []*common.TaxRept
		countcustom    int64
		// rolelimit     *common.RoleLimits
		queryBson bson.M
		customno  string //客户编号
	)

	query := req.URL.Query()
	customno = query.Get("customno")
	skipParam = query.Get("skip")
	limitParam = query.Get("limit")

	if skip, err = strconv.Atoi(skipParam); err != nil {
		skip = 0
	}

	if limit, err = strconv.Atoi(limitParam); err != nil {
		limit = 100

	}

	if customno != "" {
		qcustomno := bson.M{"customNo": customno}
		querySet = append(querySet, qcustomno)
	}

	queryBson = bson.M{"$and": querySet}

	custommap := make(map[string]interface{})
	countcustom, _ = G_CustomMgr.countHisCustomtaxbySet(queryBson)

	if customtaxinfos, err = G_CustomMgr.queryHisCustomTaxbySet(queryBson, int64(skip), int64(limit)); err != nil {
		goto ERR
	}

	custommap["customcount"] = countcustom
	custommap["custominfos"] = customtaxinfos

	if bytes, err = common.BuildResponse(0, "success", custommap); err == nil {
		resp.Write(bytes)
	} else {
		goto ERR
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

func handleHisCertiQuery(resp http.ResponseWriter, req *http.Request) {
	var (
		err   error
		bytes []byte
		// entclueinfo *common.EntClue
		querySet   []bson.M
		skipParam  string
		limitParam string
		skip       int
		limit      int
		certiinfos []*common.CertiInfo
		countcerti int64
		// rolelimit     *common.RoleLimits
		queryBson bson.M
		customno  string //客户编号
	)

	query := req.URL.Query()
	customno = query.Get("customno")
	skipParam = query.Get("skip")
	limitParam = query.Get("limit")

	if skip, err = strconv.Atoi(skipParam); err != nil {
		skip = 0
	}

	if limit, err = strconv.Atoi(limitParam); err != nil {
		limit = 100

	}

	if customno != "" {
		qcustomno := bson.M{"customNo": customno}
		querySet = append(querySet, qcustomno)
	}

	queryBson = bson.M{"$and": querySet}

	certimap := make(map[string]interface{})
	countcerti, _ = G_CustomMgr.countHisCertibySet(queryBson)

	if certiinfos, err = G_CustomMgr.queryHisCertibySet(queryBson, int64(skip), int64(limit)); err != nil {
		goto ERR
	}

	certimap["countcerti"] = countcerti
	certimap["certiinfos"] = certiinfos

	if bytes, err = common.BuildResponse(0, "success", certimap); err == nil {
		resp.Write(bytes)
	} else {
		goto ERR
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

func handleCertiQuery(resp http.ResponseWriter, req *http.Request) {
	var (
		err   error
		bytes []byte
		// entclueinfo *common.EntClue
		querySet   []bson.M
		skipParam  string
		limitParam string
		skip       int
		limit      int
		certiinfos []*common.CertiInfo
		countcerti int64
		// rolelimit     *common.RoleLimits
		queryBson   bson.M
		customno    string //客户编号
		servicemon  string //服务月份
		certists    string //凭证状态
		companyname string //公司名称
	)

	query := req.URL.Query()
	customno = query.Get("customno")
	servicemon = query.Get("servicemon")
	companyname = query.Get("companyname")
	certists = query.Get("certists")
	skipParam = query.Get("skip")
	limitParam = query.Get("limit")

	if skip, err = strconv.Atoi(skipParam); err != nil {
		skip = 0
	}

	if limit, err = strconv.Atoi(limitParam); err != nil {
		limit = 100
	}

	if companyname != "" {
		qcompanyname := bson.M{"companyName": companyname}
		querySet = append(querySet, qcompanyname)
	}

	if certists != "" {
		qcertists := bson.M{"certiSts": certists}
		querySet = append(querySet, qcertists)
	}

	if customno != "" {
		qcustomno := bson.M{"customNo": customno}
		querySet = append(querySet, qcustomno)
	}

	if servicemon != "" {
		// qservicemon2 := bson.M{"serviceMon": bson.M{"$gte": "2020-01"}}
		// querySet = append(querySet, qservicemon2)

		qservicemon := bson.M{"serviceMon": servicemon}
		querySet = append(querySet, qservicemon)

	}

	queryBson = bson.M{"$and": querySet}

	custommap := make(map[string]interface{})
	countcerti, _ = G_CustomMgr.countHisCertibySet(queryBson)

	if certiinfos, err = G_CustomMgr.queryHisCertibySet(queryBson, int64(skip), int64(limit)); err != nil {
		goto ERR
	}

	custommap["customcount"] = countcerti
	custommap["custominfos"] = certiinfos

	if bytes, err = common.BuildResponse(0, "success", custommap); err == nil {
		resp.Write(bytes)
	} else {
		goto ERR
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}
func handleDonwloadCustaxInfo(resp http.ResponseWriter, req *http.Request) {
	var (
		err   error
		bytes []byte
		// entclueinfo *common.EntClue
		querySet       []bson.M
		customtaxinfos []*common.TaxRept
		// rolelimit     *common.RoleLimits
		queryBson       bson.M
		customno        string //客户编号
		servicemon      string //服务月份
		accountant      string //主管会计
		entryaccountant string //记账会计
		agentstatus     string //代账状态
		companyname     string //公司名称
		taxmethod       string //税务核算方式
		taxcontrol      string //是否有盘控税
		taxcontrolsite  string //盘控税所在地
		taxreturnsts    string //抄报税状态  月度报税编辑页面下拉选择，选项有：抄报税已完成、抄报税异常、无需抄报税；非必填项。
		clearcard       string //清卡状态  月度报税编辑页面下拉选择，选项有：清卡已完成、清卡异常、无需清卡；非必填项。
		accountantsts   string //是否需要做账  月度报税编辑页面下拉选择，选项有：需要做账、无需做账；非必填项。
		incomests       string //进项是否已确认 月度报税编辑页面下拉选择，选项有：进项已确认、无需确认；非必选项。
		accountinginfor string //做账资料是否已全 月度报税编辑页面下拉选择，选项有：做账资料已全、无需记账；非必选项。
		accountingsts   string //记账状态 月度报税编辑页面下拉选择，选项有：记账已完成、无需记账；非必选项。
		reporttax       string //报税状态 月度报税编辑页面下拉选择，选项有：报税已完成、不需要报税；非必选项。
		certiloadsts    string //凭证装订状态  不需要报税、报税已完成
		outfile         string
		customtaxinfo   *common.TaxRept
		row             *xlsx.Row
		x               interface{}
	)

	query := req.URL.Query()
	customno = query.Get("customno")
	servicemon = query.Get("servicemon")
	entryaccountant = query.Get("entryaccountant")
	accountant = query.Get("accountant")
	agentstatus = query.Get("agentstatus")

	companyname = query.Get("companyname")
	taxmethod = query.Get("taxmethod")
	taxcontrol = query.Get("taxcontrol")
	taxcontrolsite = query.Get("taxcontrolsite")
	taxreturnsts = query.Get("taxreturnsts")
	clearcard = query.Get("clearcard")
	accountantsts = query.Get("accountantsts")
	incomests = query.Get("incomests")
	accountinginfor = query.Get("accountinginfor")
	accountingsts = query.Get("accountingsts")
	reporttax = query.Get("reporttax")
	certiloadsts = query.Get("certiloadsts")

	if clearcard != "" {
		qclearcard := bson.M{"clearCard": clearcard}
		querySet = append(querySet, qclearcard)
	}

	if reporttax != "" {
		qreporttax := bson.M{"reportTax": reporttax}
		querySet = append(querySet, qreporttax)
	}

	if certiloadsts != "" {
		qcertiloadsts := bson.M{"certiLoadSts": certiloadsts}
		querySet = append(querySet, qcertiloadsts)
	}
	if accountingsts != "" {
		qaccountingsts := bson.M{"accountingSts": accountingsts}
		querySet = append(querySet, qaccountingsts)
	}
	if accountinginfor != "" {
		qaccountinginfor := bson.M{"accountingInfor": accountinginfor}
		querySet = append(querySet, qaccountinginfor)
	}

	if incomests != "" {
		qincomests := bson.M{"incomeSts": incomests}
		querySet = append(querySet, qincomests)
	}

	if accountantsts != "" {
		qaccountantsts := bson.M{"accountantSts": accountantsts}
		querySet = append(querySet, qaccountantsts)
	}

	if taxreturnsts != "" {
		qtaxreturnsts := bson.M{"taxReturnSts": taxreturnsts}
		querySet = append(querySet, qtaxreturnsts)
	}

	if taxcontrolsite != "" {
		qtaxcontrolsite := bson.M{"taxControlSite": taxcontrolsite}
		querySet = append(querySet, qtaxcontrolsite)
	}

	if taxmethod != "" {
		qtaxmethod := bson.M{"taxMethod": taxmethod}
		querySet = append(querySet, qtaxmethod)
	}

	if taxcontrol != "" {
		qtaxcontrol := bson.M{"taxControl": taxcontrol}
		querySet = append(querySet, qtaxcontrol)
	}

	if companyname != "" {
		qcompanyname := bson.M{"companyName": bson.M{"$regex": companyname}}
		querySet = append(querySet, qcompanyname)
	}

	if agentstatus != "" {
		qagentstatus := bson.M{"agentStatus": agentstatus}
		querySet = append(querySet, qagentstatus)
	}

	if customno != "" {
		qcustomno := bson.M{"customNo": customno}
		querySet = append(querySet, qcustomno)
	}

	if servicemon != "" {
		qservicemon := bson.M{"serviceMon": bson.M{"$lte": servicemon}}
		querySet = append(querySet, qservicemon)

	}

	if entryaccountant != "" {
		qentryaccountant := bson.M{"entryAccountant": entryaccountant}
		querySet = append(querySet, qentryaccountant)
	}

	if accountant != "" {
		qaccountant := bson.M{"accountant": accountant}
		querySet = append(querySet, qaccountant)
	}

	queryBson = bson.M{"$and": querySet}

	custommap := make(map[string]interface{})

	outfile = "./downloadfile/taxrept" + common.BuildDateTodayStr4() + ".xlsx"

	// outfile = G_config.FileUrl + ":" + strconv.Itoa(G_config.ApiPort) + "/downloadfile/custom" + common.BuildDateTodayStr4() + ".xlsx"
	f := xlsx.NewFile()
	sheet, _ := f.AddSheet("custom")
	// sheet.Hidden()
	if customtaxinfos, err = G_CustomMgr.queryHisCustomTaxDownloadbySet(queryBson); err != nil {
		goto ERR
	}

	// custominfo = &common.AgentCustom{}

	for idx, _ := range customtaxinfos {
		// fmt.Println(idx)
		//写表头
		// fmt.Println(1111 + idx)
		if idx == 0 {
			// fmt.Println(idx)
			x = customtaxinfos[0]
			row = sheet.AddRow()
			// reflect.ValueOf(custominfo)
			// v := reflect.ValueOf(&custominfo)
			// n := reflect.ValueOf(&custominfo).NumField()
			t := reflect.TypeOf(x)
			if t.Kind() == reflect.Ptr {
				t = t.Elem()
			}
			// fmt.Println(t.Kind())
			if t.Kind() != reflect.Struct {
				fmt.Println("Check type error not Struct")
				return
			}
			n := t.NumField()
			for i := 0; i < n; i = i + 1 {
				cell := row.AddCell()
				cell.SetValue(t.Field(i).Name)
			}
		}
		row = sheet.AddRow()
		customtaxinfo = customtaxinfos[idx]
		row.WriteStruct(customtaxinfo, -1)
	}
	// defer row.sheet.Close()

	if err = f.Save(outfile); err != nil {
		goto ERR
	}
	custommap["filepath"] = G_config.FileUrl + ":" + strconv.Itoa(G_config.ApiPort) + "/downloadfile/taxrept" + common.BuildDateTodayStr4() + ".xlsx"

	if bytes, err = common.BuildResponse(0, "success", custommap); err == nil {
		resp.Write(bytes)
	} else {
		goto ERR
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}
func handleCustaxQuery(resp http.ResponseWriter, req *http.Request) {
	var (
		err   error
		bytes []byte
		// entclueinfo *common.EntClue
		querySet       []bson.M
		skipParam      string
		limitParam     string
		skip           int
		limit          int
		customtaxinfos []*common.TaxRept
		countcustom    int64
		// rolelimit     *common.RoleLimits
		queryBson       bson.M
		customno        string //客户编号
		servicemon      string //服务月份
		accountant      string //主管会计
		entryaccountant string //记账会计
		agentstatus     string //代账状态
		companyname     string //公司名称
		taxmethod       string //税务核算方式
		taxcontrol      string //是否有盘控税
		taxcontrolsite  string //盘控税所在地
		taxreturnsts    string //抄报税状态  月度报税编辑页面下拉选择，选项有：抄报税已完成、抄报税异常、无需抄报税；非必填项。
		clearcard       string //清卡状态  月度报税编辑页面下拉选择，选项有：清卡已完成、清卡异常、无需清卡；非必填项。
		accountantsts   string //是否需要做账  月度报税编辑页面下拉选择，选项有：需要做账、无需做账；非必填项。
		incomests       string //进项是否已确认 月度报税编辑页面下拉选择，选项有：进项已确认、无需确认；非必选项。
		accountinginfor string //做账资料是否已全 月度报税编辑页面下拉选择，选项有：做账资料已全、无需记账；非必选项。
		accountingsts   string //记账状态 月度报税编辑页面下拉选择，选项有：记账已完成、无需记账；非必选项。
		reporttax       string //报税状态 月度报税编辑页面下拉选择，选项有：报税已完成、不需要报税；非必选项。
		certiloadsts    string //凭证装订状态  不需要报税、报税已完成

	)

	query := req.URL.Query()
	customno = query.Get("customno")
	servicemon = query.Get("servicemon")
	entryaccountant = query.Get("entryaccountant")
	accountant = query.Get("accountant")
	agentstatus = query.Get("agentstatus")

	companyname = query.Get("companyname")
	taxmethod = query.Get("taxmethod")
	taxcontrol = query.Get("taxcontrol")
	taxcontrolsite = query.Get("taxcontrolsite")
	taxreturnsts = query.Get("taxreturnsts")
	clearcard = query.Get("clearcard")
	accountantsts = query.Get("accountantsts")
	incomests = query.Get("incomests")
	accountinginfor = query.Get("accountinginfor")
	accountingsts = query.Get("accountingsts")
	reporttax = query.Get("reporttax")
	certiloadsts = query.Get("certiloadsts")

	skipParam = query.Get("skip")
	limitParam = query.Get("limit")

	if skip, err = strconv.Atoi(skipParam); err != nil {
		skip = 0
	}

	if limit, err = strconv.Atoi(limitParam); err != nil {
		limit = 100
	}

	if clearcard != "" {
		qclearcard := bson.M{"clearCard": clearcard}
		querySet = append(querySet, qclearcard)
	}

	if reporttax != "" {
		qreporttax := bson.M{"reportTax": reporttax}
		querySet = append(querySet, qreporttax)
	}

	if certiloadsts != "" {
		qcertiloadsts := bson.M{"certiLoadSts": certiloadsts}
		querySet = append(querySet, qcertiloadsts)
	}
	if accountingsts != "" {
		qaccountingsts := bson.M{"accountingSts": accountingsts}
		querySet = append(querySet, qaccountingsts)
	}
	if accountinginfor != "" {
		qaccountinginfor := bson.M{"accountingInfor": accountinginfor}
		querySet = append(querySet, qaccountinginfor)
	}

	if incomests != "" {
		qincomests := bson.M{"incomeSts": incomests}
		querySet = append(querySet, qincomests)
	}

	if accountantsts != "" {
		qaccountantsts := bson.M{"accountantSts": accountantsts}
		querySet = append(querySet, qaccountantsts)
	}

	if taxreturnsts != "" {
		qtaxreturnsts := bson.M{"taxReturnSts": taxreturnsts}
		querySet = append(querySet, qtaxreturnsts)
	}

	if taxcontrolsite != "" {
		qtaxcontrolsite := bson.M{"taxControlSite": taxcontrolsite}
		querySet = append(querySet, qtaxcontrolsite)
	}

	if taxmethod != "" {
		qtaxmethod := bson.M{"taxMethod": taxmethod}
		querySet = append(querySet, qtaxmethod)
	}

	if taxcontrol != "" {
		qtaxcontrol := bson.M{"taxControl": taxcontrol}
		querySet = append(querySet, qtaxcontrol)
	}

	if companyname != "" {
		qcompanyname := bson.M{"companyName": bson.M{"$regex": companyname}}
		querySet = append(querySet, qcompanyname)
	}

	if agentstatus != "" {
		qagentstatus := bson.M{"agentStatus": agentstatus}
		querySet = append(querySet, qagentstatus)
	}

	if customno != "" {
		qcustomno := bson.M{"customNo": customno}
		querySet = append(querySet, qcustomno)
	}

	if servicemon != "" {
		qservicemon := bson.M{"serviceMon": bson.M{"$lte": servicemon}}
		querySet = append(querySet, qservicemon)

	}

	if entryaccountant != "" {
		qentryaccountant := bson.M{"entryAccountant": entryaccountant}
		querySet = append(querySet, qentryaccountant)
	}

	if accountant != "" {
		qaccountant := bson.M{"accountant": accountant}
		querySet = append(querySet, qaccountant)
	}

	queryBson = bson.M{"$and": querySet}

	custommap := make(map[string]interface{})
	countcustom, _ = G_CustomMgr.countCustombySet(queryBson)

	if customtaxinfos, err = G_CustomMgr.queryCustomTaxbySet(queryBson, int64(skip), int64(limit)); err != nil {
		goto ERR
	}

	custommap["customcount"] = countcustom
	custommap["custominfos"] = customtaxinfos

	if bytes, err = common.BuildResponse(0, "success", custommap); err == nil {
		resp.Write(bytes)
	} else {
		goto ERR
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

func handleCertiSave(resp http.ResponseWriter, req *http.Request) {
	var (
		err      error
		bytes    []byte
		certi    *common.CertiInfo
		certistr string
		custom   *common.AgentCustom
	)

	if err = req.ParseForm(); err != nil {
		goto ERR
	}
	certistr = req.PostForm.Get("certistr")
	// fmt.Println(customtaxstr)

	if err = json.Unmarshal([]byte(certistr), &certi); err != nil {
		goto ERR
	}

	if certi.CustomNo != "" && certi.ServiceMon != "" {
		custom = G_CustomMgr.getCustomByNo(certi.CustomNo)
		if custom != nil {
			certi.CompanyName = custom.CompanyName
			certi.CustomNo = custom.CustomNo

			if err = G_CustomMgr.updCustomCerti(certi); err != nil {
				goto ERR
			}
			if err = G_CustomMgr.saveCertitax(certi); err != nil {
				goto ERR
			}
			if bytes, err = common.BuildResponse(0, "success", "凭证管理信息维护成功"); err == nil {
				resp.Write(bytes)
			}

		} else {
			if bytes, err = common.BuildResponse(-1, "error", "该客户不存在"); err == nil {
				resp.Write(bytes)
			}

		}
	} else {
		if bytes, err = common.BuildResponse(-1, "error", "客户号不能为空或者服务月份不能为空"); err == nil {
			resp.Write(bytes)
		}
	}
	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

func handleCustaxSave(resp http.ResponseWriter, req *http.Request) {
	var (
		err          error
		bytes        []byte
		customtax    *common.TaxRept
		customtaxstr string
		custom       *common.AgentCustom
	)

	if err = req.ParseForm(); err != nil {
		goto ERR
	}
	customtaxstr = req.PostForm.Get("customtaxstr")
	// fmt.Println(customtaxstr)

	if err = json.Unmarshal([]byte(customtaxstr), &customtax); err != nil {
		goto ERR
	}

	if customtax.CustomNo != "" && customtax.ServiceMon != "" {
		custom = G_CustomMgr.getCustomByNo(customtax.CustomNo)
		if custom != nil {
			customtax.TaxAll = customtax.ValueAddedTax + customtax.BusinessIncomeTax + customtax.AdditionalTax + customtax.StampTax + customtax.PersonalIncomeTax
			customtax.CompanyName = custom.CompanyName
			customtax.AgentStatus = custom.AgentStatus
			customtax.TaxMethod = custom.TaxMethod
			customtax.Accountant = custom.Accountant
			customtax.EntryAccountant = custom.EntryAccountant
			customtax.TaxControl = custom.TaxControl
			customtax.TaxControlSite = custom.TaxControlSite
			customtax.SocialCreditCode = custom.SocialCreditCode
			customtax.CustomNo = custom.CustomNo

			if err = G_CustomMgr.updCustomtax(customtax); err != nil {
				goto ERR
			}
			if err = G_CustomMgr.saveCustomtax(customtax); err != nil {
				goto ERR
			}
			if bytes, err = common.BuildResponse(0, "success", "新增月度报税信息成功"); err == nil {
				resp.Write(bytes)
			}

		} else {
			if bytes, err = common.BuildResponse(-1, "error", "该客户不存在"); err == nil {
				resp.Write(bytes)
			}

		}
	} else {
		if bytes, err = common.BuildResponse(-1, "error", "客户号不能为空或者服务月份不能为空"); err == nil {
			resp.Write(bytes)
		}
	}
	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

func handleBillingAccountantBatch(resp http.ResponseWriter, req *http.Request) {
	var (
		err               error
		bytes             []byte
		customs           []string
		customnosstr      string
		billingaccountant string
		querySet          []bson.M
		queryBson         bson.M
		// rolelimit     *common.RoleLimits
	)

	if err = req.ParseForm(); err != nil {
		goto ERR
	}
	customnosstr = req.PostForm.Get("customnos")
	customs = strings.Split(customnosstr, ",")
	billingaccountant = req.PostForm.Get("billingaccountant")
	if customnosstr != "" {
		q_customNo := bson.M{"customNo": bson.M{"$in": customs}}
		querySet = append(querySet, q_customNo)
	}

	queryBson = bson.M{"$and": querySet}

	if err = G_CustomMgr.updCustomBillingAccountantbySet(queryBson, billingaccountant); err != nil {
		if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
			resp.Write(bytes)
		}
	} else {
		if bytes, err = common.BuildResponse(0, "success", "批量更新开票会计成功"); err == nil {
			resp.Write(bytes)
		}
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

func handleUpdCheckStatus(resp http.ResponseWriter, req *http.Request) {
	var (
		err         error
		bytes       []byte
		checkyear   string
		customnostr string
		checkdate   string
		checkcause  string
		checkstatus string
		// rolelimit     *common.RoleLimits
	)

	if err = req.ParseForm(); err != nil {
		goto ERR
	}
	customnostr = req.PostForm.Get("customno")
	checkyear = req.PostForm.Get("checkyear")
	checkstatus = req.PostForm.Get("checkstatus")
	checkcause = req.PostForm.Get("checkcause")
	checkdate = req.PostForm.Get("checkdate")

	if err = G_CustomMgr.updCustomCheckerStatus(customnostr, checkyear, checkstatus, checkcause, checkdate); err != nil {
		if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
			resp.Write(bytes)
		}
	} else {
		if bytes, err = common.BuildResponse(0, "success", "更新年检状态成功"); err == nil {
			resp.Write(bytes)
		}
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

func handleCheckerBatch(resp http.ResponseWriter, req *http.Request) {
	var (
		err          error
		bytes        []byte
		customs      []string
		customnosstr string
		checker      string
		querySet     []bson.M
		queryBson    bson.M
		// rolelimit     *common.RoleLimits
	)

	if err = req.ParseForm(); err != nil {
		goto ERR
	}
	customnosstr = req.PostForm.Get("customnos")
	customs = strings.Split(customnosstr, ",")
	checker = req.PostForm.Get("checker")

	if customnosstr != "" {
		q_customNo := bson.M{"customNo": bson.M{"$in": customs}}
		querySet = append(querySet, q_customNo)
	}

	queryBson = bson.M{"$and": querySet}

	if err = G_CustomMgr.updCustomCheckerbySet(queryBson, checker); err != nil {
		if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
			resp.Write(bytes)
		}
	} else {
		if bytes, err = common.BuildResponse(0, "success", "批量年检专员成功"); err == nil {
			resp.Write(bytes)
		}
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

func handleResCustomMgrUpdBatch(resp http.ResponseWriter, req *http.Request) {
	var (
		err          error
		bytes        []byte
		customs      []string
		customnosstr string
		rescustommgr string
		querySet     []bson.M
		queryBson    bson.M
		// rolelimit     *common.RoleLimits
	)

	if err = req.ParseForm(); err != nil {
		goto ERR
	}
	customnosstr = req.PostForm.Get("customnos")
	customs = strings.Split(customnosstr, ",")
	rescustommgr = req.PostForm.Get("rescustommgr")
	if rescustommgr != "" {
		q_customNo := bson.M{"customNo": bson.M{"$in": customs}}
		querySet = append(querySet, q_customNo)
	}

	queryBson = bson.M{"$and": querySet}

	if err = G_CustomMgr.updResCustomMgrBatchbySet(queryBson, rescustommgr); err != nil {
		if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
			resp.Write(bytes)
		}
	} else {
		if bytes, err = common.BuildResponse(0, "success", "批量更新负责客户经理成功"); err == nil {
			resp.Write(bytes)
		}
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

func handleCustomMgrUpdBatch(resp http.ResponseWriter, req *http.Request) {
	var (
		err          error
		bytes        []byte
		customs      []string
		customnosstr string
		custommgr    string
		querySet     []bson.M
		queryBson    bson.M
		// rolelimit     *common.RoleLimits
	)

	if err = req.ParseForm(); err != nil {
		goto ERR
	}
	customnosstr = req.PostForm.Get("customnos")
	customs = strings.Split(customnosstr, ",")
	custommgr = req.PostForm.Get("custommgr")
	if customnosstr != "" {
		q_customNo := bson.M{"customNo": bson.M{"$in": customs}}
		querySet = append(querySet, q_customNo)
	}

	queryBson = bson.M{"$and": querySet}

	if err = G_CustomMgr.updCustomMgrBatchbySet(queryBson, custommgr); err != nil {
		if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
			resp.Write(bytes)
		}
	} else {
		if bytes, err = common.BuildResponse(0, "success", "批量更新客户经理成功"); err == nil {
			resp.Write(bytes)
		}
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

func handleEntryAccountantBatch(resp http.ResponseWriter, req *http.Request) {
	var (
		err             error
		bytes           []byte
		customs         []string
		customnosstr    string
		entryaccountant string
		querySet        []bson.M
		queryBson       bson.M
		// rolelimit     *common.RoleLimits
	)

	if err = req.ParseForm(); err != nil {
		goto ERR
	}
	customnosstr = req.PostForm.Get("customnos")
	customs = strings.Split(customnosstr, ",")
	entryaccountant = req.PostForm.Get("entryaccountant")
	if customnosstr != "" {
		q_customNo := bson.M{"customNo": bson.M{"$in": customs}}
		querySet = append(querySet, q_customNo)
	}

	queryBson = bson.M{"$and": querySet}

	if err = G_CustomMgr.updCustomEntryAccountantbySet(queryBson, entryaccountant); err != nil {
		if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
			resp.Write(bytes)
		}
	} else {
		if bytes, err = common.BuildResponse(0, "success", "批量更新记账会计成功"); err == nil {
			resp.Write(bytes)
		}
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

func handleUpdaccountantBatch(resp http.ResponseWriter, req *http.Request) {
	var (
		err          error
		bytes        []byte
		customs      []string
		customnosstr string
		accountant   string
		querySet     []bson.M
		queryBson    bson.M
		// rolelimit     *common.RoleLimits
	)

	if err = req.ParseForm(); err != nil {
		goto ERR
	}
	customnosstr = req.PostForm.Get("customnos")
	customs = strings.Split(customnosstr, ",")
	accountant = req.PostForm.Get("accountant")
	if customnosstr != "" {
		q_customNo := bson.M{"customNo": bson.M{"$in": customs}}
		querySet = append(querySet, q_customNo)
	}

	queryBson = bson.M{"$and": querySet}

	if err = G_CustomMgr.updCustomAccountantbySet(queryBson, accountant); err != nil {
		if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
			resp.Write(bytes)
		}
	} else {
		if bytes, err = common.BuildResponse(0, "success", "批量更新主管会计成功"); err == nil {
			resp.Write(bytes)
		}
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

func handleCustomSave(resp http.ResponseWriter, req *http.Request) {
	var (
		err           error
		bytes         []byte
		custom        *common.AgentCustom
		custominfostr string
		// querySet      []bson.M
		customno string
		// queryBson     bson.M
		customcount int64
		// rolelimit     *common.RoleLimits
	)

	if err = req.ParseForm(); err != nil {
		goto ERR
	}
	custominfostr = req.PostForm.Get("custominfo")

	if err = json.Unmarshal([]byte(custominfostr), &custom); err != nil {
		goto ERR
	}

	if custom.AgentFeeEndDate != "" && len(custom.AgentFeeEndDate) > 10 {
		if bytes, err = common.BuildResponse(-1, "error", "代账费截止日期格式异常"); err == nil {
			resp.Write(bytes)
		}
		return
	}

	if custom.CustomNo == "" {
		if custom.TaxMethod != "" {
			if custom.CustomNo == "" {
				switch custom.TaxMethod {
				case "小规模纳税人":
					customno = "A-"
				case "一般纳税人":
					customno = "B-"
				case "个体":
					customno = "C-"
				default:
					customno = "D-"
				}
				//只需要按总的客户数来生成编号
				// querycustid := bson.M{"customNo": bson.M{"$regex": customno, "$options": "$i"}}
				// querySet = append(querySet, querycustid)
				// queryBson = bson.M{"$and": querySet}
				customcount, err = G_CustomMgr.countCustom()
				custom.CustomNo = customno + strconv.FormatInt(customcount+1, 10)
				custom.CreateTime = common.BuildDateTodayStr2()
				//保存
				if err = G_CustomMgr.saveCustom(custom); err == nil {
					G_OrderMgr.updOrderSts(custom.OrderNo, "已转为代账客户")
					if bytes, err = common.BuildResponse(0, "success", custom); err == nil {
						resp.Write(bytes)
					}
				} else {
					goto ERR
				}
			}
		} else {
			if bytes, err = common.BuildResponse(-1, "error", "税务核算方式必须为一般纳税人、小规模纳税人、个体"); err == nil {
				resp.Write(bytes)
			}
		}
	} else {
		custom.CreateTime = common.BuildDateTodayStr2()
		if err = G_CustomMgr.saveCustom(custom); err == nil {
			if bytes, err = common.BuildResponse(0, "success", custom); err == nil {
				resp.Write(bytes)
			}
		} else {
			goto ERR
		}
	}
	// fmt.Println(cluein

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}
func handleDownloadCustomInfo(resp http.ResponseWriter, req *http.Request) {
	var (
		err   error
		bytes []byte
		// entclueinfo *common.EntClue
		querySet    []bson.M
		custominfos []*common.AgentCustom

		custominfo *common.AgentCustom
		// rolelimit     *common.RoleLimits

		queryBson bson.M

		customno             string //客户编号
		begincustomdate      string //
		endcustomdate        string //
		beginbuilddate       string //工商成立开始时间
		endbuilddate         string //工商成立结束时间
		companyname          string //公司名称
		taxmethod            string //税务核算方式
		agentstatus          string //代账状态
		custommgr            string //客户经理
		entryaccountant      string //记账会计
		accountant           string //主管会计
		billingaccountant    string //开票会计
		beginagentfeeenddate string //代账费开始日期
		endagentfeeenddate   string //代账费结束日期
		buildregion          string //注册区域
		legalperson          string //法人
		intype               string //转化来源
		customlevel          string //客户等级
		nilreturn            string //是否零申报
		taxcontrol           string //是否有盘控税
		taxcontrolsite       string //盘控税所在地
		bussyearreport       string //工商年报是否已完成
		orderno              string //订单编号
		checkyear            string //年检年份
		checkstatus          string //年检状态
		checkcause           string //年检未完成原因
		checker              string //年检专员
		outfile              string
		row                  *xlsx.Row
		x                    interface{}
	)

	query := req.URL.Query()
	billingaccountant = query.Get("billingaccountant")
	customno = query.Get("customno")
	beginbuilddate = query.Get("beginbuilddate")
	endbuilddate = query.Get("endbuilddate")
	companyname = query.Get("companyname")
	taxmethod = query.Get("taxmethod")
	agentstatus = query.Get("agentstatus")
	custommgr = query.Get("custommgr")
	entryaccountant = query.Get("entryaccountant")
	accountant = query.Get("accountant")
	beginagentfeeenddate = query.Get("beginagentfeeenddate")
	endagentfeeenddate = query.Get("endagentfeeenddate")
	buildregion = query.Get("buildregion")

	legalperson = query.Get("legalperson")
	intype = query.Get("intype")
	customlevel = query.Get("customlevel")
	nilreturn = query.Get("nilreturn")
	taxcontrol = query.Get("taxcontrol")
	taxcontrolsite = query.Get("taxcontrolsite")
	bussyearreport = query.Get("bussyearreport")
	orderno = query.Get("orderno")

	checkyear = query.Get("checkyear")
	checkstatus = query.Get("checkstatus")
	checkcause = query.Get("checkcause")
	checker = query.Get("checker")

	begincustomdate = query.Get("begincustomdate")
	endcustomdate = query.Get("endcustomdate")

	if checker != "" {
		qchecker := bson.M{"checker": checker}
		querySet = append(querySet, qchecker)
	}

	if checkcause != "" {
		qcheckcause := bson.M{"checkCause": checkcause}
		querySet = append(querySet, qcheckcause)
	}

	if checkstatus != "" {
		qcheckstatus := bson.M{"checkStatus": checkstatus}
		querySet = append(querySet, qcheckstatus)
	}

	if checkyear != "" {
		qcheckyear := bson.M{"checkYear": checkyear}
		querySet = append(querySet, qcheckyear)
	}

	if billingaccountant != "" {
		qbillingaccountant := bson.M{"billingAccountant": billingaccountant}
		querySet = append(querySet, qbillingaccountant)
	}

	if customno != "" {
		qtype := bson.M{"customNo": customno}
		querySet = append(querySet, qtype)
	}
	if orderno != "" {
		qorderno := bson.M{"orderNo": orderno}
		querySet = append(querySet, qorderno)
	}
	if companyname != "" {
		qcompanyname := bson.M{"companyName": bson.M{"$regex": companyname, "$options": "$i"}}
		querySet = append(querySet, qcompanyname)
	}

	if taxmethod != "" {
		qtype := bson.M{"taxMethod": taxmethod}
		querySet = append(querySet, qtype)
	}
	if agentstatus != "" {
		qagentstatus := bson.M{"agentStatus": agentstatus}
		querySet = append(querySet, qagentstatus)
	}
	if entryaccountant != "" {
		qentryaccountant := bson.M{"entryAccountant": entryaccountant}
		querySet = append(querySet, qentryaccountant)
	}
	if accountant != "" {
		qaccountant := bson.M{"accountant": accountant}
		querySet = append(querySet, qaccountant)
	}
	if legalperson != "" {
		qlegalperson := bson.M{"legalPerson": legalperson}
		querySet = append(querySet, qlegalperson)
	}
	if buildregion != "" {
		qbuildregion := bson.M{"buildRegion": buildregion}
		querySet = append(querySet, qbuildregion)
	}
	if intype != "" {
		qintype := bson.M{"inType": intype}
		querySet = append(querySet, qintype)
	}
	if customlevel != "" {
		qcustomlevel := bson.M{"customLevel": customlevel}
		querySet = append(querySet, qcustomlevel)
	}
	if nilreturn != "" {
		qnilreturn := bson.M{"nilReturn": nilreturn}
		querySet = append(querySet, qnilreturn)
	}
	if taxcontrol != "" {
		qtaxcontrol := bson.M{"taxControl": taxcontrol}
		querySet = append(querySet, qtaxcontrol)
	}
	if taxcontrolsite != "" {
		qtaxcontrolsite := bson.M{"taxControlSite": taxcontrolsite}
		querySet = append(querySet, qtaxcontrolsite)
	}
	if taxcontrolsite != "" {
		qtaxcontrolsite := bson.M{"taxControlSite": taxcontrolsite}
		querySet = append(querySet, qtaxcontrolsite)
	}
	if custommgr != "" {
		qcustommgr := bson.M{"customMgr": custommgr}
		querySet = append(querySet, qcustommgr)
	}

	if bussyearreport != "" {
		qbussyearreport := bson.M{"bussYearReport": bussyearreport}
		querySet = append(querySet, qbussyearreport)
	}

	if beginbuilddate != "" {
		qbegindate := bson.M{"buildDate": bson.M{"$gte": beginbuilddate}}
		querySet = append(querySet, qbegindate)
		// setElements = append(setElements, bson.E{"createTime", createtime})
	}

	if endcustomdate != "" {
		qendcustomdate := bson.M{"customDate": bson.M{"$lte": endcustomdate}}
		querySet = append(querySet, qendcustomdate)
		// setElements = append(setElements, bson.E{"createTime", createtime})
	}

	if begincustomdate != "" {
		qbegincustomdate := bson.M{"customDate": bson.M{"$gte": begincustomdate}}
		querySet = append(querySet, qbegincustomdate)
		// setElements = append(setElements, bson.E{"createTime", createtime})
	}

	if endbuilddate != "" {
		qenddate := bson.M{"buildDate": bson.M{"$lte": endbuilddate}}
		querySet = append(querySet, qenddate)
		// setElements = append(setElements, bson.E{"createTime", createtime})
	}

	if beginagentfeeenddate != "" {
		qbegindate := bson.M{"agentFeeEndDate": bson.M{"$gte": beginagentfeeenddate}}
		querySet = append(querySet, qbegindate)
		// setElements = append(setElements, bson.E{"createTime", createtime})
	}

	if endagentfeeenddate != "" {
		qenddate := bson.M{"agentFeeEndDate": bson.M{"$lte": endagentfeeenddate}}
		querySet = append(querySet, qenddate)
		// setElements = append(setElements, bson.E{"createTime", createtime})
	}

	queryBson = bson.M{"$and": querySet}

	custommap := make(map[string]interface{})

	outfile = "./downloadfile/custom" + common.BuildDateTodayStr4() + ".xlsx"

	// outfile = G_config.FileUrl + ":" + strconv.Itoa(G_config.ApiPort) + "/downloadfile/custom" + common.BuildDateTodayStr4() + ".xlsx"
	f := xlsx.NewFile()
	sheet, _ := f.AddSheet("custom")
	// sheet.Hidden()
	if custominfos, err = G_CustomMgr.queryDownloadCustombySet(queryBson); err != nil {
		goto ERR
	}

	// custominfo = &common.AgentCustom{}

	for idx, _ := range custominfos {
		// fmt.Println(idx)
		//写表头
		// fmt.Println(1111 + idx)
		if idx == 0 {
			// fmt.Println(idx)
			x = custominfos[0]
			row = sheet.AddRow()
			// reflect.ValueOf(custominfo)
			// v := reflect.ValueOf(&custominfo)
			// n := reflect.ValueOf(&custominfo).NumField()
			t := reflect.TypeOf(x)
			if t.Kind() == reflect.Ptr {
				t = t.Elem()
			}
			// fmt.Println(t.Kind())
			if t.Kind() != reflect.Struct {
				fmt.Println("Check type error not Struct")
				return
			}
			n := t.NumField()
			for i := 0; i < n; i = i + 1 {
				cell := row.AddCell()
				cell.SetValue(t.Field(i).Tag.Get("uname"))
			}
		}
		row = sheet.AddRow()
		custominfo = custominfos[idx]
		row.WriteStruct(custominfo, -1)
	}
	// defer row.Sheet.Close()

	if err = f.Save(outfile); err != nil {
		goto ERR
	}
	custommap["filepath"] = G_config.FileUrl + ":" + strconv.Itoa(G_config.ApiPort) + "/downloadfile/custom" + common.BuildDateTodayStr4() + ".xlsx"

	if bytes, err = common.BuildResponse(0, "success", custommap); err == nil {
		resp.Write(bytes)
	} else {
		goto ERR
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

func handleCustomquery(resp http.ResponseWriter, req *http.Request) {
	var (
		err   error
		bytes []byte
		// entclueinfo *common.EntClue
		querySet    []bson.M
		skipParam   string
		limitParam  string
		skip        int
		limit       int
		custominfos []*common.AgentCustom
		countcustom int64
		// rolelimit     *common.RoleLimits

		queryBson bson.M

		customno             string //客户编号
		begincustomdate      string //
		endcustomdate        string //
		beginbuilddate       string //工商成立开始时间
		endbuilddate         string //工商成立结束时间
		companyname          string //公司名称
		taxmethod            string //税务核算方式
		agentstatus          string //代账状态
		custommgr            string //客户经理
		entryaccountant      string //记账会计
		accountant           string //主管会计
		billingaccountant    string //开票会计
		beginagentfeeenddate string //代账费开始日期
		endagentfeeenddate   string //代账费结束日期
		buildregion          string //注册区域
		legalperson          string //法人
		intype               string //转化来源
		customlevel          string //客户等级
		nilreturn            string //是否零申报
		taxcontrol           string //是否有盘控税
		taxcontrolsite       string //盘控税所在地
		bussyearreport       string //工商年报是否已完成
		orderno              string //订单编号
		checkyear            string //年检年份
		checkstatus          string //年检状态
		checkcause           string //年检未完成原因
		checker              string //年检专员
		taxplatetype         string
		servicesite          string
	)

	query := req.URL.Query()
	billingaccountant = query.Get("billingaccountant")
	customno = query.Get("customno")
	beginbuilddate = query.Get("beginbuilddate")
	endbuilddate = query.Get("endbuilddate")
	companyname = query.Get("companyname")
	taxmethod = query.Get("taxmethod")
	agentstatus = query.Get("agentstatus")
	custommgr = query.Get("custommgr")
	entryaccountant = query.Get("entryaccountant")
	accountant = query.Get("accountant")
	beginagentfeeenddate = query.Get("beginagentfeeenddate")
	endagentfeeenddate = query.Get("endagentfeeenddate")
	buildregion = query.Get("buildregion")

	legalperson = query.Get("legalperson")
	intype = query.Get("intype")
	customlevel = query.Get("customlevel")
	nilreturn = query.Get("nilreturn")
	taxcontrol = query.Get("taxcontrol")
	taxcontrolsite = query.Get("taxcontrolsite")
	taxplatetype = query.Get("taxplatetype")
	servicesite = query.Get("servicesite")

	bussyearreport = query.Get("bussyearreport")
	orderno = query.Get("orderno")

	checkyear = query.Get("checkyear")
	checkstatus = query.Get("checkstatus")
	checkcause = query.Get("checkcause")
	checker = query.Get("checker")

	begincustomdate = query.Get("begincustomdate")
	endcustomdate = query.Get("endcustomdate")

	skipParam = query.Get("skip")
	limitParam = query.Get("limit")

	if skip, err = strconv.Atoi(skipParam); err != nil {
		skip = 0
	}

	if limit, err = strconv.Atoi(limitParam); err != nil {
		limit = 100
	}

	if checker != "" {
		qchecker := bson.M{"checker": checker}
		querySet = append(querySet, qchecker)
	}

	if checkcause != "" {
		qcheckcause := bson.M{"checkCause": checkcause}
		querySet = append(querySet, qcheckcause)
	}

	if checkstatus != "" {
		qcheckstatus := bson.M{"checkStatus": checkstatus}
		querySet = append(querySet, qcheckstatus)
	}

	if checkyear != "" {
		qcheckyear := bson.M{"checkYear": checkyear}
		querySet = append(querySet, qcheckyear)
	}

	if billingaccountant != "" {
		qbillingaccountant := bson.M{"billingAccountant": billingaccountant}
		querySet = append(querySet, qbillingaccountant)
	}

	if customno != "" {
		qtype := bson.M{"customNo": customno}
		querySet = append(querySet, qtype)
	}
	if orderno != "" {
		qorderno := bson.M{"orderNo": orderno}
		querySet = append(querySet, qorderno)
	}
	if companyname != "" {
		qcompanyname := bson.M{"companyName": bson.M{"$regex": companyname, "$options": "$i"}}
		querySet = append(querySet, qcompanyname)
	}

	if taxmethod != "" {
		qtype := bson.M{"taxMethod": taxmethod}
		querySet = append(querySet, qtype)
	}
	if agentstatus != "" {
		qagentstatus := bson.M{"agentStatus": agentstatus}
		querySet = append(querySet, qagentstatus)
	}
	if entryaccountant != "" {
		qentryaccountant := bson.M{"entryAccountant": entryaccountant}
		querySet = append(querySet, qentryaccountant)
	}
	if accountant != "" {
		qaccountant := bson.M{"accountant": accountant}
		querySet = append(querySet, qaccountant)
	}
	if legalperson != "" {
		qlegalperson := bson.M{"legalPerson": legalperson}
		querySet = append(querySet, qlegalperson)
	}
	if buildregion != "" {
		qbuildregion := bson.M{"buildRegion": buildregion}
		querySet = append(querySet, qbuildregion)
	}
	if intype != "" {
		qintype := bson.M{"inType": intype}
		querySet = append(querySet, qintype)
	}
	if customlevel != "" {
		qcustomlevel := bson.M{"customLevel": customlevel}
		querySet = append(querySet, qcustomlevel)
	}
	if nilreturn != "" {
		qnilreturn := bson.M{"nilReturn": nilreturn}
		querySet = append(querySet, qnilreturn)
	}
	if taxcontrol != "" {
		qtaxcontrol := bson.M{"taxControl": taxcontrol}
		querySet = append(querySet, qtaxcontrol)
	}
	if taxcontrolsite != "" {
		qtaxcontrolsite := bson.M{"taxControlSite": taxcontrolsite}
		querySet = append(querySet, qtaxcontrolsite)
	}
	if taxplatetype != "" {
		qtaxplatetype := bson.M{"taxPlateType": taxplatetype}
		querySet = append(querySet, qtaxplatetype)
	}

	if servicesite != "" {
		qtaxplatetype := bson.M{"serviceSite": servicesite}
		querySet = append(querySet, qtaxplatetype)
	}

	if custommgr != "" {
		qcustommgr := bson.M{"customMgr": custommgr}
		querySet = append(querySet, qcustommgr)
	}

	if bussyearreport != "" {
		qbussyearreport := bson.M{"bussYearReport": bussyearreport}
		querySet = append(querySet, qbussyearreport)
	}

	if beginbuilddate != "" {
		qbegindate := bson.M{"buildDate": bson.M{"$gte": beginbuilddate}}
		querySet = append(querySet, qbegindate)
		// setElements = append(setElements, bson.E{"createTime", createtime})
	}

	if endcustomdate != "" {
		qendcustomdate := bson.M{"customDate": bson.M{"$lte": endcustomdate}}
		querySet = append(querySet, qendcustomdate)
		// setElements = append(setElements, bson.E{"createTime", createtime})
	}

	if begincustomdate != "" {
		qbegincustomdate := bson.M{"customDate": bson.M{"$gte": begincustomdate}}
		querySet = append(querySet, qbegincustomdate)
		// setElements = append(setElements, bson.E{"createTime", createtime})
	}

	if endbuilddate != "" {
		qenddate := bson.M{"buildDate": bson.M{"$lte": endbuilddate}}
		querySet = append(querySet, qenddate)
		// setElements = append(setElements, bson.E{"createTime", createtime})
	}

	if beginagentfeeenddate != "" {
		qbegindate := bson.M{"agentFeeEndDate": bson.M{"$gte": beginagentfeeenddate}}
		querySet = append(querySet, qbegindate)
		// setElements = append(setElements, bson.E{"createTime", createtime})
	}

	if endagentfeeenddate != "" {
		qenddate := bson.M{"agentFeeEndDate": bson.M{"$lte": endagentfeeenddate}}
		querySet = append(querySet, qenddate)
		// setElements = append(setElements, bson.E{"createTime", createtime})
	}

	queryBson = bson.M{"$and": querySet}

	custommap := make(map[string]interface{})
	countcustom, _ = G_CustomMgr.countCustombySet(queryBson)
	// fmt.Println(countclue)

	if custominfos, err = G_CustomMgr.queryCustombySet(queryBson, int64(skip), int64(limit)); err != nil {
		goto ERR
	}
	custommap["customcount"] = countcustom
	custommap["custominfos"] = custominfos
	if bytes, err = common.BuildResponse(0, "success", custommap); err == nil {
		resp.Write(bytes)
	} else {
		goto ERR
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

func (customMgr *CustomMgr) saveCertitax(certi *common.CertiInfo) (err error) {

	var (
		// resultOne *mongo.InsertOneResult
		filter   *common.CertiFilter
		doccount int64
		// update *common.HostInfo
	)
	filter = &common.CertiFilter{
		CustomNo:   certi.CustomNo,
		ServiceMon: certi.ServiceMon,
	}

	if doccount, err = customMgr.CertiColl.CountDocuments(context.TODO(), filter, &options.CountOptions{}); err != nil {
		return
	}
	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))
	if doccount > 0 {
		customMgr.CertiColl.UpdateOne(context.TODO(), filter, bson.M{"$set": certi})
	} else {
		customMgr.CertiColl.InsertOne(context.TODO(), certi)
	}

	return
}

func (customMgr *CustomMgr) saveCustomtax(customtax *common.TaxRept) (err error) {

	var (
		// resultOne *mongo.InsertOneResult
		filter   *common.CustomTaxFilter
		doccount int64
		// update *common.HostInfo
	)

	filter = &common.CustomTaxFilter{
		CustomNo:   customtax.CustomNo,
		ServiceMon: customtax.ServiceMon,
	}

	if doccount, err = customMgr.CustomTaxColl.CountDocuments(context.TODO(), filter, &options.CountOptions{}); err != nil {
		return
	}
	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))

	customtax.CreateTime = common.BuildDateTodayStr2()

	if doccount > 0 {
		customMgr.CustomTaxColl.UpdateOne(context.TODO(), filter, bson.M{"$set": customtax})
	} else {
		customMgr.CustomTaxColl.InsertOne(context.TODO(), customtax)
	}

	return
}

func (customMgr *CustomMgr) updCustomCerti(customtax *common.CertiInfo) (err error) {

	var (
		// resultOne *mongo.InsertOneResult
		filter   *common.CustomNoFilter
		doccount int64
		// update *common.HostInfo
	)

	filter = &common.CustomNoFilter{
		CustomNo: customtax.CustomNo,
	}

	if doccount, err = customMgr.CustomColl.CountDocuments(context.TODO(), filter, &options.CountOptions{}); err != nil {
		return
	}
	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))

	if doccount > 0 {
		customMgr.CustomColl.UpdateOne(context.TODO(), filter, bson.M{"$set": customtax})
	}

	return
}

func (customMgr *CustomMgr) updCustomtax(customtax *common.TaxRept) (err error) {

	var (
		// resultOne *mongo.InsertOneResult
		filter   *common.CustomNoFilter
		doccount int64
		// update *common.HostInfo
	)

	filter = &common.CustomNoFilter{
		CustomNo: customtax.CustomNo,
	}

	if doccount, err = customMgr.CustomColl.CountDocuments(context.TODO(), filter, &options.CountOptions{}); err != nil {
		return
	}
	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))

	if doccount > 0 {
		customMgr.CustomColl.UpdateOne(context.TODO(), filter, bson.M{"$set": customtax})
	}

	return
}

func (customMgr *CustomMgr) saveCustom(custom *common.AgentCustom) (err error) {

	var (
		// resultOne *mongo.InsertOneResult
		filter *common.CustomNoFilter
		// doccount  int64
		tmpcustom *common.AgentCustom
		// update *common.HostInfo
		acctchangecount int
	)

	filter = &common.CustomNoFilter{
		CustomNo: custom.CustomNo,
	}

	customMgr.CustomColl.FindOne(context.TODO(), filter).Decode(&tmpcustom)

	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))

	if tmpcustom != nil {
		if tmpcustom.AgentStatus != custom.AgentStatus {
			custom.AgentStatusChangeTime = common.BuildDateTodayStr2()
		} else {
			custom.AgentStatusChangeTime = tmpcustom.AgentStatusChangeTime
		}

		if tmpcustom.Accountant != custom.Accountant {

			if acctchangecount, err = strconv.Atoi(tmpcustom.AccountantChangeCount); err != nil {
				acctchangecount = 0
			}
			acctchangecount = acctchangecount + 1
			stringacctchangecount := strconv.Itoa(acctchangecount)
			custom.AccountantChangeCount = stringacctchangecount
			custom.AccountantChangeTime = common.BuildTimeNowStr()
		}
		if custom.AgentBeginDate == "" {
			custom.AgentBeginDate = tmpcustom.AgentBeginDate
		}

		if custom.AgentFeeEndDate == "" {
			custom.AgentFeeEndDate = tmpcustom.AgentFeeEndDate
		}

		customMgr.CustomColl.UpdateOne(context.TODO(), filter, bson.M{"$set": custom})

	} else {
		custom.CustomDate = common.BuildDateTodayStr2()
		custom.AgentStatusChangeTime = common.BuildDateTodayStr2()
		customMgr.CustomColl.InsertOne(context.TODO(), custom)
	}

	return
}

func (customMgr *CustomMgr) getCustomByOrderNo(orderNo string) (custom *common.AgentCustom) {

	var (
		// resultOne *mongo.InsertOneResult
		filter *common.CustomOrderNoFilter
		// update *common.HostInfo
	)

	filter = &common.CustomOrderNoFilter{
		OrderNo: orderNo,
	}

	customMgr.CustomColl.FindOne(context.TODO(), filter).Decode(&custom)
	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))
	return
}

func (customMgr *CustomMgr) getCustomByNo(customNo string) (custom *common.AgentCustom) {

	var (
		// resultOne *mongo.InsertOneResult
		filter *common.CustomNoFilter
		// update *common.HostInfo
	)

	filter = &common.CustomNoFilter{
		CustomNo: customNo,
	}

	customMgr.CustomColl.FindOne(context.TODO(), filter).Decode(&custom)
	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))
	return
}

func (customMgr *CustomMgr) updCustomServerAllDate(customNo string, customsvrbegdate string, customsvrenddate string) (err error) {

	var (
		// resultOne *mongo.InsertOneResult
		filter   *common.CustomNoFilter
		doccount int64
		// update *common.HostInfo
	)

	filter = &common.CustomNoFilter{
		CustomNo: customNo,
	}

	if doccount, err = customMgr.CustomColl.CountDocuments(context.TODO(), filter, &options.CountOptions{}); err != nil {
		return
	}
	if doccount > 0 {
		customMgr.CustomColl.FindOneAndUpdate(context.TODO(), filter, bson.M{"$set": bson.M{"agentFeeEndDate": customsvrenddate, "agentBeginDate": customsvrbegdate}})
	}
	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))
	return
}

func (customMgr *CustomMgr) updCustomServerDate(customNo string, customsvrdate string) (err error) {

	var (
		// resultOne *mongo.InsertOneResult
		filter   *common.CustomNoFilter
		doccount int64
		// update *common.HostInfo
	)

	filter = &common.CustomNoFilter{
		CustomNo: customNo,
	}

	if doccount, err = customMgr.CustomColl.CountDocuments(context.TODO(), filter, &options.CountOptions{}); err != nil {
		return
	}
	if doccount > 0 {
		customMgr.CustomColl.FindOneAndUpdate(context.TODO(), filter, bson.M{"$set": bson.M{"agentFeeEndDate": customsvrdate}})
	}
	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))
	return
}

func (customMgr *CustomMgr) countCustom() (countCustom int64, err error) {
	var (
		// resultOne *mongo.InsertOneResult
		ctx context.Context
		// update *common.HostInfo
	)
	ctx, _ = context.WithTimeout(context.Background(), 15*time.Second)

	// fmt.Println(1)
	countCustom, err = customMgr.CustomColl.CountDocuments(ctx, bson.M{})

	return
}

func (customMgr *CustomMgr) countHisCertibySet(setElements bson.M) (countCerti int64, err error) {
	var (
		// resultOne *mongo.InsertOneResult
		ctx context.Context
		// update *common.HostInfo
	)
	ctx, _ = context.WithTimeout(context.Background(), 15*time.Second)
	if len(setElements["$and"].([]primitive.M)) == 0 {
		// fmt.Println(0)
		countCerti, err = customMgr.CertiColl.CountDocuments(ctx, bson.M{})
	} else {
		// fmt.Println(1)
		countCerti, err = customMgr.CertiColl.CountDocuments(ctx, setElements)
	}
	return
}

func (customMgr *CustomMgr) countHisCustomtaxbySet(setElements bson.M) (countCustom int64, err error) {
	var (
		// resultOne *mongo.InsertOneResult
		ctx context.Context
		// update *common.HostInfo
	)
	ctx, _ = context.WithTimeout(context.Background(), 15*time.Second)
	if len(setElements["$and"].([]primitive.M)) == 0 {
		// fmt.Println(0)
		countCustom, err = customMgr.CustomTaxColl.CountDocuments(ctx, bson.M{})
	} else {
		// fmt.Println(1)
		countCustom, err = customMgr.CustomTaxColl.CountDocuments(ctx, setElements)
	}
	return
}

func (customMgr *CustomMgr) countCustombySet(setElements bson.M) (countCustom int64, err error) {
	var (
		// resultOne *mongo.InsertOneResult
		ctx context.Context
		// update *common.HostInfo
	)
	ctx, _ = context.WithTimeout(context.Background(), 15*time.Second)
	if len(setElements["$and"].([]primitive.M)) == 0 {
		// fmt.Println(0)
		countCustom, err = customMgr.CustomColl.CountDocuments(ctx, bson.M{})
	} else {
		// fmt.Println(1)
		countCustom, err = customMgr.CustomColl.CountDocuments(ctx, setElements)
	}
	return
}

func InitCustomMgr() (err error) {

	G_CustomMgr = &CustomMgr{
		client:        G_MongoMgr.client,
		CustomColl:    G_MongoMgr.MongdbConnect.Collection("custom"),
		CustomTaxColl: G_MongoMgr.MongdbConnect.Collection("customtax"),
		CertiColl:     G_MongoMgr.MongdbConnect.Collection("certi"),
	}

	return
}

func (customMgr *CustomMgr) queryDownloadCustombySet(setElements bson.M) (customs []*common.AgentCustom, err error) {

	var (
		// resultOne *mongo.InsertOneResult
		cursor     *mongo.Cursor
		custom     *common.AgentCustom
		findopt    *options.FindOptions
		ctx        context.Context
		customSort *common.SortById
		// update *common.HostInfo
	)

	ctx, _ = context.WithTimeout(context.Background(), 10*time.Second)

	findopt = &options.FindOptions{}
	customSort = &common.SortById{
		SortOrder: -1,
	}

	findopt.SetSort(customSort)
	findopt.SetBatchSize(2000)

	if len(setElements["$and"].([]primitive.M)) == 0 {
		// fmt.Println(0)
		cursor, err = customMgr.CustomColl.Find(context.TODO(), bson.M{}, findopt)
	} else {
		// fmt.Println(1)
		cursor, err = customMgr.CustomColl.Find(context.TODO(), setElements, findopt)
	}
	defer cursor.Close(ctx)

	for cursor.Next(ctx) {
		custom = &common.AgentCustom{}
		if err = cursor.Decode(custom); err != nil {
			continue
		}
		custom.ClientelePhone1 = ""
		custom.ClientelePhone2 = ""
		custom.CustomMgrPhone = ""
		custom.LegalPhone = ""
		customs = append(customs, custom)
	}
	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))
	return
}

func (customMgr *CustomMgr) queryCustombySet(setElements bson.M, skip int64, limit int64) (customs []*common.AgentCustom, err error) {

	var (
		// resultOne *mongo.InsertOneResult
		cursor     *mongo.Cursor
		custom     *common.AgentCustom
		findopt    *options.FindOptions
		ctx        context.Context
		customSort *common.SortById
		// update *common.HostInfo
	)

	ctx, _ = context.WithTimeout(context.Background(), 10*time.Second)

	findopt = &options.FindOptions{}
	customSort = &common.SortById{
		SortOrder: -1,
	}
	findopt.SetSort(customSort)

	if limit > 0 && skip >= 0 {
		findopt.SetLimit(limit)
		findopt.SetSkip(limit * skip)

	} else {
		return
	}
	if len(setElements["$and"].([]primitive.M)) == 0 {
		// fmt.Println(0)
		cursor, err = customMgr.CustomColl.Find(context.TODO(), bson.M{}, findopt)
	} else {
		// fmt.Println(1)
		cursor, err = customMgr.CustomColl.Find(context.TODO(), setElements, findopt)
	}
	defer cursor.Close(ctx)

	for cursor.Next(ctx) {
		custom = &common.AgentCustom{}
		if err = cursor.Decode(custom); err != nil {
			continue
		}
		customs = append(customs, custom)
	}
	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))
	return
}

func (customMgr *CustomMgr) queryHisCertibySet(setElements bson.M, skip int64, limit int64) (certiinfos []*common.CertiInfo, err error) {

	var (
		// resultOne *mongo.InsertOneResult
		cursor    *mongo.Cursor
		certi     *common.CertiInfo
		findopt   *options.FindOptions
		ctx       context.Context
		certiSort *common.SortById
		// update *common.HostInfo
	)

	ctx, _ = context.WithTimeout(context.Background(), 10*time.Second)

	findopt = &options.FindOptions{}
	certiSort = &common.SortById{
		SortOrder: -1,
	}
	findopt.SetSort(certiSort)

	if limit > 0 && skip >= 0 {
		findopt.SetLimit(limit)
		findopt.SetSkip(limit * skip)
	} else {
		return
	}
	if len(setElements["$and"].([]primitive.M)) == 0 {

		cursor, err = customMgr.CertiColl.Find(context.TODO(), bson.M{}, findopt)
	} else {
		cursor, err = customMgr.CertiColl.Find(context.TODO(), setElements, findopt)
	}
	defer cursor.Close(ctx)

	for cursor.Next(ctx) {
		certi = &common.CertiInfo{}
		if err = cursor.Decode(certi); err != nil {
			continue
		}
		certiinfos = append(certiinfos, certi)
	}
	return
}

func (customMgr *CustomMgr) queryHisCustomTaxDownloadbySet(setElements bson.M) (taxrepts []*common.TaxRept, err error) {

	var (
		// resultOne *mongo.InsertOneResult
		cursor     *mongo.Cursor
		taxrept    *common.TaxRept
		findopt    *options.FindOptions
		ctx        context.Context
		customSort *common.SortById
		// update *common.HostInfo
	)

	ctx, _ = context.WithTimeout(context.Background(), 10*time.Second)

	findopt = &options.FindOptions{}
	customSort = &common.SortById{
		SortOrder: -1,
	}
	findopt.SetSort(customSort)
	findopt.SetBatchSize(2000)

	if len(setElements["$and"].([]primitive.M)) == 0 {
		cursor, err = customMgr.CustomTaxColl.Find(context.TODO(), bson.M{}, findopt)
	} else {
		cursor, err = customMgr.CustomTaxColl.Find(context.TODO(), setElements, findopt)
	}
	defer cursor.Close(ctx)

	for cursor.Next(ctx) {
		taxrept = &common.TaxRept{}
		if err = cursor.Decode(taxrept); err != nil {
			continue
		}
		taxrepts = append(taxrepts, taxrept)
	}
	return
}

func (customMgr *CustomMgr) queryHisCustomTaxbySet(setElements bson.M, skip int64, limit int64) (taxrepts []*common.TaxRept, err error) {

	var (
		// resultOne *mongo.InsertOneResult
		cursor     *mongo.Cursor
		taxrept    *common.TaxRept
		findopt    *options.FindOptions
		ctx        context.Context
		customSort *common.SortById
		// update *common.HostInfo
	)

	ctx, _ = context.WithTimeout(context.Background(), 10*time.Second)

	findopt = &options.FindOptions{}
	customSort = &common.SortById{
		SortOrder: -1,
	}
	findopt.SetSort(customSort)

	if limit > 0 && skip >= 0 {
		findopt.SetLimit(limit)
		findopt.SetSkip(limit * skip)
	} else {
		return
	}
	if len(setElements["$and"].([]primitive.M)) == 0 {
		cursor, err = customMgr.CustomTaxColl.Find(context.TODO(), bson.M{}, findopt)
	} else {
		cursor, err = customMgr.CustomTaxColl.Find(context.TODO(), setElements, findopt)
	}
	defer cursor.Close(ctx)

	for cursor.Next(ctx) {
		taxrept = &common.TaxRept{}
		if err = cursor.Decode(taxrept); err != nil {
			continue
		}
		taxrepts = append(taxrepts, taxrept)
	}
	return
}

func (customMgr *CustomMgr) queryCustomDownloadTaxbySet(setElements bson.M) (taxrepts []*common.TaxRept, err error) {

	var (
		// resultOne *mongo.InsertOneResult
		cursor     *mongo.Cursor
		taxrept    *common.TaxRept
		findopt    *options.FindOptions
		ctx        context.Context
		customSort *common.SortById
		// update *common.HostInfo
	)

	ctx, _ = context.WithTimeout(context.Background(), 10*time.Second)

	findopt = &options.FindOptions{}
	customSort = &common.SortById{
		SortOrder: -1,
	}

	findopt.SetSort(customSort)
	findopt.SetBatchSize(2000)

	findopt.SetSort(customSort)

	if len(setElements["$and"].([]primitive.M)) == 0 {
		cursor, err = customMgr.CustomColl.Find(context.TODO(), bson.M{}, findopt)
	} else {
		cursor, err = customMgr.CustomColl.Find(context.TODO(), setElements, findopt)
	}
	defer cursor.Close(ctx)

	// now := time.Now()
	// yesterMon := now.AddDate(0, -1, 0)
	// yesmonstr := yesterMon.Format("2006-01")

	for cursor.Next(ctx) {
		taxrept = &common.TaxRept{}
		if err = cursor.Decode(taxrept); err != nil {
			continue
		}
		// if taxrept.ServiceMon != yesmonstr {
		// 	taxrept.ServiceMon = yesmonstr
		// 	taxrept.TaxReturnSts = ""
		// 	taxrept.ClearCard = ""        //清卡状态  月度报税编辑页面下拉选择，选项有：清卡已完成、清卡异常、无需清卡；非必填项。
		// 	taxrept.AccountantSts = ""    //是否需要做账  月度报税编辑页面下拉选择，选项有：需要做账、无需做账；非必填项。
		// 	taxrept.PaySheet = ""         //工资表  月度报税编辑页面下拉选择，选项有：和上个月一样、已发钉钉、无需做工资；非必选项。
		// 	taxrept.Statreceipt = ""      //对账单回单 月度报税编辑页面下拉选择，选项有：有银行对账单、无银行对账单；非必选项。
		// 	taxrept.IncomeSts = ""        //进项是否已确认 月度报税编辑页面下拉选择，选项有：进项已确认、无需确认；非必选项。
		// 	taxrept.EstimatedCost = ""    //暂估成本  编辑页面文本格式，非必填项
		// 	taxrept.FrontIncomeTax = ""   //拟缴纳企业所得税金额  编辑页面文本格式，非必填项
		// 	taxrept.AccountingInfor = ""  //做账资料是否已全 月度报税编辑页面下拉选择，选项有：做账资料已全、无需记账；非必选项。
		// 	taxrept.AccountingSts = ""    //记账状态 月度报税编辑页面下拉选择，选项有：记账已完成、无需记账；非必选项。
		// 	taxrept.ReportTax = ""        //报税状态 月度报税编辑页面下拉选择，选项有：报税已完成、不需要报税；非必选项。
		// 	taxrept.CertiLoadSts = ""     //凭证装订状态  不需要报税、报税已完成
		// 	taxrept.OperatingIncome = 0   //营业收入  编辑页面输入，数字，有小数点，非必填项
		// 	taxrept.ValueAddedTax = 0     //增值税 编辑页面输入，数字，有小数点，非必填项
		// 	taxrept.BusinessIncomeTax = 0 //企业所得税 编辑页面输入，数字，有小数点，非必填项
		// 	taxrept.AdditionalTax = 0     //附加税 编辑页面输入，数字，有小数点，非必填项
		// 	taxrept.StampTax = 0          //印花税 编辑页面输入，数字，有小数点，非必填项
		// 	taxrept.PersonalIncomeTax = 0 //个税 编辑页面输入，数字，有小数点，非必填项
		// 	taxrept.TaxAll = 0
		// }
		taxrepts = append(taxrepts, taxrept)
	}
	return
}

func (customMgr *CustomMgr) queryCustomTaxbySet(setElements bson.M, skip int64, limit int64) (taxrepts []*common.TaxRept, err error) {

	var (
		// resultOne *mongo.InsertOneResult
		cursor     *mongo.Cursor
		taxrept    *common.TaxRept
		findopt    *options.FindOptions
		ctx        context.Context
		customSort *common.SortById
		// update *common.HostInfo
	)

	ctx, _ = context.WithTimeout(context.Background(), 10*time.Second)

	findopt = &options.FindOptions{}
	customSort = &common.SortById{
		SortOrder: -1,
	}
	findopt.SetSort(customSort)

	if limit > 0 && skip >= 0 {
		findopt.SetLimit(limit)
		findopt.SetSkip(limit * skip)
	} else {
		return
	}
	if len(setElements["$and"].([]primitive.M)) == 0 {
		cursor, err = customMgr.CustomColl.Find(context.TODO(), bson.M{}, findopt)
	} else {
		cursor, err = customMgr.CustomColl.Find(context.TODO(), setElements, findopt)
	}
	defer cursor.Close(ctx)

	now := time.Now()
	yesterMon := now.AddDate(0, -1, 0)
	yesmonstr := yesterMon.Format("2006-01")

	for cursor.Next(ctx) {
		taxrept = &common.TaxRept{}
		if err = cursor.Decode(taxrept); err != nil {
			continue
		}
		if taxrept.ServiceMon != yesmonstr {
			taxrept.ServiceMon = yesmonstr
			taxrept.TaxReturnSts = ""
			taxrept.ClearCard = ""        //清卡状态  月度报税编辑页面下拉选择，选项有：清卡已完成、清卡异常、无需清卡；非必填项。
			taxrept.AccountantSts = ""    //是否需要做账  月度报税编辑页面下拉选择，选项有：需要做账、无需做账；非必填项。
			taxrept.PaySheet = ""         //工资表  月度报税编辑页面下拉选择，选项有：和上个月一样、已发钉钉、无需做工资；非必选项。
			taxrept.Statreceipt = ""      //对账单回单 月度报税编辑页面下拉选择，选项有：有银行对账单、无银行对账单；非必选项。
			taxrept.IncomeSts = ""        //进项是否已确认 月度报税编辑页面下拉选择，选项有：进项已确认、无需确认；非必选项。
			taxrept.EstimatedCost = ""    //暂估成本  编辑页面文本格式，非必填项
			taxrept.FrontIncomeTax = ""   //拟缴纳企业所得税金额  编辑页面文本格式，非必填项
			taxrept.AccountingInfor = ""  //做账资料是否已全 月度报税编辑页面下拉选择，选项有：做账资料已全、无需记账；非必选项。
			taxrept.AccountingSts = ""    //记账状态 月度报税编辑页面下拉选择，选项有：记账已完成、无需记账；非必选项。
			taxrept.ReportTax = ""        //报税状态 月度报税编辑页面下拉选择，选项有：报税已完成、不需要报税；非必选项。
			taxrept.CertiLoadSts = ""     //凭证装订状态  不需要报税、报税已完成
			taxrept.OperatingIncome = 0   //营业收入  编辑页面输入，数字，有小数点，非必填项
			taxrept.ValueAddedTax = 0     //增值税 编辑页面输入，数字，有小数点，非必填项
			taxrept.BusinessIncomeTax = 0 //企业所得税 编辑页面输入，数字，有小数点，非必填项
			taxrept.AdditionalTax = 0     //附加税 编辑页面输入，数字，有小数点，非必填项
			taxrept.StampTax = 0          //印花税 编辑页面输入，数字，有小数点，非必填项
			taxrept.PersonalIncomeTax = 0 //个税 编辑页面输入，数字，有小数点，非必填项
			taxrept.TaxAll = 0
		}
		taxrepts = append(taxrepts, taxrept)
	}
	return
}

func (customMgr *CustomMgr) updCustomAccountantbySet(setElements bson.M, accountant string) (err error) {

	var (
		// resultOne *mongo.InsertOneResult
		// update *common.HostInfo
		cursor          *mongo.Cursor
		ctx             context.Context
		custominfo      *common.AgentCustom
		acctchangecount int
	)
	// fmt.Println("updCustomAccountantbySet")
	ctx, _ = context.WithTimeout(context.Background(), 10*time.Second)
	if len(setElements["$and"].([]primitive.M)) == 0 {
		// fmt.Println(0)

	} else {
		// fmt.Println(setElements)
		cursor, _ = customMgr.CustomColl.Find(ctx, setElements)
		defer cursor.Close(ctx)

		for cursor.Next(ctx) {
			custominfo = &common.AgentCustom{}
			if err = cursor.Decode(custominfo); err != nil {
				continue
			}
			// fmt.Println(custominfo.CustomNo)
			if custominfo.Accountant != accountant {
				// fmt.Println(custominfo)
				if acctchangecount, err = strconv.Atoi(custominfo.AccountantChangeCount); err != nil {
					acctchangecount = 0
				}
				acctchangecount = acctchangecount + 1
				stringacctchangecount := strconv.Itoa(acctchangecount)

				customMgr.CustomColl.UpdateOne(ctx, bson.M{"customNo": custominfo.CustomNo}, bson.M{"$set": bson.M{"accountant": accountant, "accountantChangeCount": stringacctchangecount, "accountantChangeTime": common.BuildTimeNowStr()}})
			}
		}

		// _, err = customMgr.CustomColl.UpdateMany(ctx, setElements, bson.M{"$set": bson.M{"accountant": accountant}})
	}
	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))
	return
}

func (customMgr *CustomMgr) updCustomCheckerbySet(setElements bson.M, checker string) (err error) {

	var (
	// resultOne *mongo.InsertOneResult
	// update *common.HostInfo
	)

	if len(setElements["$and"].([]primitive.M)) == 0 {
		// fmt.Println(0)

	} else {
		// fmt.Println(1)
		_, err = customMgr.CustomColl.UpdateMany(context.TODO(), setElements, bson.M{"$set": bson.M{"checker": checker}})
	}
	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))
	return
}

func (customMgr *CustomMgr) updResCustomMgrBatchbySet(setElements bson.M, rescustommgr string) (err error) {

	var (
	// resultOne *mongo.InsertOneResult
	// update *common.HostInfo
	)

	if len(setElements["$and"].([]primitive.M)) == 0 {
		// fmt.Println(0)

	} else {
		// fmt.Println(1)
		_, err = customMgr.CustomColl.UpdateMany(context.TODO(), setElements, bson.M{"$set": bson.M{"resCustomMgr": rescustommgr}})
	}
	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))
	return
}

func (customMgr *CustomMgr) updCustomMgrBatchbySet(setElements bson.M, custommgr string) (err error) {

	var (
	// resultOne *mongo.InsertOneResult
	// update *common.HostInfo
	)

	if len(setElements["$and"].([]primitive.M)) == 0 {
		// fmt.Println(0)

	} else {
		// fmt.Println(1)
		_, err = customMgr.CustomColl.UpdateMany(context.TODO(), setElements, bson.M{"$set": bson.M{"customMgr": custommgr}})
	}
	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))
	return
}

func (customMgr *CustomMgr) updCustomEntryAccountantbySet(setElements bson.M, entryaccountant string) (err error) {

	var (
	// resultOne *mongo.InsertOneResult
	// update *common.HostInfo
	)

	if len(setElements["$and"].([]primitive.M)) == 0 {
		// fmt.Println(0)

	} else {
		// fmt.Println(1)
		_, err = customMgr.CustomColl.UpdateMany(context.TODO(), setElements, bson.M{"$set": bson.M{"entryAccountant": entryaccountant}})
	}
	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))
	return
}
func (customMgr *CustomMgr) updCustomBillingAccountantbySet(setElements bson.M, billingaccountant string) (err error) {

	var (
	// resultOne *mongo.InsertOneResult
	// update *common.HostInfo
	)

	if len(setElements["$and"].([]primitive.M)) == 0 {
		// fmt.Println(0)

	} else {
		// fmt.Println(1)
		_, err = customMgr.CustomColl.UpdateMany(context.TODO(), setElements, bson.M{"$set": bson.M{"billingAccountant": billingaccountant}})
	}
	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))
	return
}

func (customMgr *CustomMgr) updCustomCheckerStatus(customno string, checkyear string, checkstatus string, checkcause string, checkdate string) (err error) {

	var (
		// resultOne *mongo.InsertOneResult
		filter *common.CustomNoFilter
		// update *common.HostInfo
	)

	filter = &common.CustomNoFilter{
		CustomNo: customno,
	}

	if _, err = customMgr.CustomColl.UpdateOne(context.TODO(), filter, bson.M{"$set": bson.M{"checkYear": checkyear, "checkStatus": checkstatus, "checkCause": checkcause, "checkDate": checkdate}}); err != nil {
		return
	}

	return
}
